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

PHP array foreach, join

巴扎黑
Release: 2023-03-02 15:50:02
Original
1046 people have browsed it

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template