How to loop through an array in php to get the values

angryTom
Release: 2023-02-28 08:10:01
Original
3656 people have browsed it

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] );
    }
}
?>
Copy after login

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 => &#39;foo&#39;,   
             1 => false,   
             2 => -1,   
             3 => null,   
             4 => &#39;&#39;  
          );   
print_r(array_filter($entry));   
?>
Copy after login

The output value is:

Array   
(   
    [0] => foo   
    [2] => -1   
)
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!