0

I want to avoid doing multiple conditionals per key value - a case in which , say, "$first_node['logo'];" is not avalable

        foreach ( $arr as $key => $value ) {
         // I want to avoid conditional here for each node


         $first_node         = $value[0];
         $logo             = $first_node['logo'];
         $name            = $first_node['name'];
         break;
        }
php_needs
  • 45
  • 4
  • Why would you put it in a loop and then break after the first iteration? https://stackoverflow.com/questions/1921421/get-the-first-element-of-an-array – Mike Feb 09 '18 at 19:10

2 Answers2

0

Use isset.

$logo = isset($first_node['logo']) ? $first_node['logo']:null;
falselight
  • 527
  • 7
  • 11
  • The are more values, how do I do it in one conditional for all - in this case for name and logo plus any others – php_needs Feb 13 '18 at 16:49
0

Short and simple, if you're using >= PHP7 use the coalesce operator

$name = $first_node['name'] ?? null;

If you're using an older version

$name = isset($first_node['name']) ? $first_node['name'] : null; 
gonzie
  • 203
  • 1
  • 10
  • The second one will actually produce undefined index warnings if it's not set. – Mike Feb 09 '18 at 19:41
  • The are more values, how do I do it in one conditional for all - in this case for name and logo plus any others – php_needs Feb 13 '18 at 16:49
  • @php_needs You would have to keep an array of all the possible variable keys. Loop through the array and check if the key exists in first_node, if now set it to null. – gonzie Feb 13 '18 at 16:51