Short and safe array traversal in PHP

藏色散人
Release: 2023-04-08 12:42:01
forward
2288 people have browsed it

Short and safe array traversal in PHP

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

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

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) {
    // ...
  }
}
Copy after login

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) {
  // ...
}
Copy after login

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

$a = is_null($b) ? $default : $b;
$a = $b ?? $default;
Copy after login

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!

Related labels:
php
source:segmentfault.com
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