$v)" to loop through the array $arr; then use "if($v)" within the loop to judge each item Whether there is a value; finally output $arr[$k] when the if condition is established."/> $v)" to loop through the array $arr; then use "if($v)" within the loop to judge each item Whether there is a value; finally output $arr[$k] when the if condition is established.">
Home > Article > Backend Development > How to loop through an array in php to get the values
php How to loop an array to get the values
1. Use foreach or while, use these two The syntax structure is used to output valuable items or delete empty elements in the array. The simple code is as follows:
<?php foreach( $arr as $k=>$v){ if( $v ){ echo $arr[$k]; }else{ // unset( $arr[$k] ); } } ?>
foreach copies the currently operated array. Each time foreach is operated, a variable is copied. Page If there are too many foreach in it, it will be a lot of consumption.
2. Use the array_filter function, which uses a callback function to filter the array. If there is no callback function, the default is to delete items with a false value in the array.
<?php $entry = array( 0 => 'foo', 1 => false, 2 => -1, 3 => null, 4 => '' ); print_r(array_filter($entry)); ?>
The output value is:
Array ( [0] => foo [2] => -1 )
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of How to loop through an array in php to get the values. For more information, please follow other related articles on the PHP Chinese website!