Home >Backend Development >PHP Tutorial >PHP array foreach, join
1. The use of foreach
For example: $arr = array("one", "two", "three");
reset($arr);//Put the internal pointer of the array to the first element and return this The value of the element. On failure, returns FALSE.
//Array loop output 1
foreach ($arr as $value) {
echo 'Value = '.$value.'
';
}
//Array loop output 2
foreach ($ arr as $key => $value) {
echo "Key: $key; Value: $value
n";
}
Second, join Combine the array elements into a string
$in = join("', '", $arr);
3. Solutions to foreach-related exceptions
1. Problem Warning: Invalid argument supplied for foreach() in Perfect solution
Solution: Change the variables in foreach, Use is_array() to judge, or force conversion to array
For example
Php code
function getPartsNum($jsonStr){
$total = 0;
if( $jsonStr && ($jsonStr != 'NAN' ) && ($jsonStr != '[]') ) {
$detail = json_decode($jsonStr);
if(is_array($detail)){//or foreach ((array)$detail as $d) (Foreach ($ Detail as $ d) {
$ Total+= $ d-& gt; num;