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

PHP array foreach, join

巴扎黑
巴扎黑Original
2016-11-30 11:57:12918browse

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;

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