Home  >  Article  >  Backend Development  >  PHP array foreach, join

PHP array foreach, join

巴扎黑
巴扎黑Original
2016-12-01 09:49:511034browse

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.'df250b2156c434f3390392d09b1c9563';
}
//Array loop output 2
foreach ($ arr as $key => $value) {
echo "Key: $key; Value: $valuedf250b2156c434f3390392d09b1c9563n";
}

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)){//或foreach ( (array)$detail as $d)  
            foreach ($detail as $d){  
                $total += $d->num;  
            }  
        }  
    }  
    return $total;  
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn