简体   繁体   中英

Excluding array keys that start with '#' from foreach in PHP?

I have a Drupal form array that uses a prefix of '#' to indicate that a given array key contains metadata instead of actual values. How can I loop through all array elements except those whose keys begin with '#'?

foreach( $array as $key => $value ) {
    if( $key[0] === "#" ) {
        continue;
    }

    //Do work
}

You can use continue to skip to the next iteration in your loop when the current key starts with a # . One way to get the first character is using substr() .

foreach ($array as $key => $value) {
    if (substr($key, 0, 1) === '#') continue;
    //do stuff
}

Try this:

<?php
function deleteElements(&$v, $k) {
   global $newArray;

   if(substr($k, 0, 1) !== '#') {
      $newArray[$k] = $v;
   }
}

$arr = array('as'=>'Test','#df'=>'this will not come','gh'=>'no test','#e'=>'again!');
$newArray = array(); // this will contain non-metadata keys
array_walk( $arr, 'deleteElements' );

//$newArrayis now..
$newArray = array('as'=>'Test','gh'=>'no test');
?>

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM