Home > front end >  Unable to output array in general loop
Unable to output array in general loop

Time:10-29

I created some variables and tried to output them in a loop. Displays all variables except array ($d)

How to output this array($d) to the general loop along with other variables?

$a = 1;        
$b = 1.2;      
$c = "xopa";   
$d = [32];     
$e = true;     
$f = null;     
 
foreach([$a, $b, $c, $d, $e, $f] as $items){  // general loop, here, in theory, $d should be displayed
echo $items. "<br>";
}

CodePudding user response:

Apologies for my first answer I misread and didn't take a look at the variable values. $d is an array so you need to check if the item is an array before echo using is_array()

$a = 1;
$b = 1.2;
$c = "xopa";
$d = [32];
$e = true;
$f = null;

foreach([$a, $b, $c, $d, $e, $f] as $items) {
  if ( is_array($items) ) {
    foreach ( $items as $child ):
      echo $child ."<br>";
    endforeach;
  } else {
  echo $items . "<br>";
  }
}

You could also pass the array through a function and loop though multiple arrays so you don't overload your code with multiple loops.

function show_array_values($arr) {
  foreach($arr as $items) {
    if ( is_array($items) ) {
      show_array_values($items);
    } else {
    echo $items . "<br>";
    }
  }
}

show_array_values([$a, $b, $c, $d, $e, $f]);
  •  Tags:  
  • php
  • Related