Home  >  Article  >  Backend Development  >  Short and safe array traversal in PHP

Short and safe array traversal in PHP

藏色散人
藏色散人forward
2020-02-19 11:50:552277browse

Short and safe array traversal in PHP

When writing PHP array traversal, we usually write like this:

foreach ($definition['keys'] as $id => $val) {
  // ...
}

But in fact this will cause an important problem: if $definition['keys '] If it is not defined, an error will occur in the array variable (that is, foreach) at this time.

Recommended: "php Training"

So, we have advanced to this:

if (!empty($definition['keys']) {
  foreach ($definition['keys'] as $id => $val) {
    // ...
  }
}

Is it very common? We just need to include another layer of if judgments outside. This ensures safe array traversal.

However, this does not meet the brief requirement, so with the convenience of PHP7, we can write it like this:

foreach ($definition['keys'] ?? [] as $id => $val) {
  // ...
}

Isn’t it very neat! Hahaha, then understand here?? It can be understood this way:

$a = is_null($b) ? $default : $b;
$a = $b ?? $default;

is equivalent to doing an is_null($b) operation.

For more programming related content, please pay attention to the Programming Introduction column on the php Chinese website!

The above is the detailed content of Short and safe array traversal in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete