targeting nested foreach loop array in php

I want to foreach loop through the $tabs[‘downloads’] subarray element (see bottom of following snippet) within the parent foreach $content[‘tabs’] loop. My attempt is not working. I get an Invalid argument. Suggestions are appreciated.

Sample of $content array:

$content=
[tabs' => [
    0 => [
      'label' => 'Afoxé',
      'downloads' => [
            0 => 'afoxe2.mscz',
            1 => 'afoxe2.pdf'],
      'content' => "blah blah",
    ],
]

Nested foreach loop:

<? $i = 1; foreach($content['tabs'] as $key => $tab):
 $tabid=$tab['label'] . "-" . $tabsuffix; ?>
 <div class="tab-pane fade <?= ($i == 1 ? "show active" : "")?>" id="pills-<?=$tabid?>" role="tabpanel"
     aria-labelledby="pills-<?=$tabid?>-tab" tabindex="0">

     <?= $Parsedown->text($tab["content"]) ?>
   
     <? foreach($tab['downloads'] as $download): ?>
     <a class="btn btn-orange blob text-white" role="button" href="../public/<?= $download ?>"
         download="<?= $download ?>"><?= $download ?></a>
     <? endforeach; ?>
 </div>
 <? $i++; endforeach; ?>

>Solution :

The only undefined index I see in your code is the video field.

That is easily fixable with the use of the Null Coalescing Operator. This only works with PHP 7+ What it does is return its first operand if it exists and is not null; otherwise it returns its second operand.

As an alternative you can always use if(isset($tab['video'])) before using the tested key anywhere else.

There is also the $tabsuffix but I will assume that is defined before the foreach.

However, if, for example, not all your entries have the downloads key, you should also handle that:

<? $i = 1; 
foreach($content['tabs'] as $key => $tab):
 $tabid=$tab['label'] . "-" . $tabsuffix; ?>
 <div class="tab-pane fade <?= ($i == 1 ? "show active" : "")?>" id="pills-<?=$tabid?>" role="tabpanel"
     aria-labelledby="pills-<?=$tabid?>-tab" tabindex="0">

     <? if( stripos(str_replace(' ', '', $tab['video'] ?? ''), '</iframe>' ) !== false )  : // <--- check this line ?>
     <div class="ratio ratio-16x9">
         <?= $tab["video"] ?>
     </div>
     <? endif; ?>

     <?= $Parsedown->text($tab["content"]) ?>
   
     <? foreach($tab['downloads'] ?? [] as $download): // <--- and this line ?>
     <a class="btn btn-orange blob text-white" role="button" href="../public/<?= $download ?>"
         download="<?= $download ?>"><?= $download ?></a>
     <? endforeach; ?>
 </div>
 <? $i++; endforeach; ?>

You can see this code working here. I have also added data with a video and one without the downloads key

Leave a Reply