Home > Blockchain >  How Can I Echo Out Array Items In An Organzied Way?
How Can I Echo Out Array Items In An Organzied Way?

Time:01-07

I want to echo out the content of this array in a 1, 2 way

$arr = array("name", "john", "lastname", "doe", "age", "55");

so I wish for it to look like

name = john
lastname = doe
age = 55

And my code currently looks like this

for ($x=0;$x<count($arr)/2;$x  ) {
        echo $arr[$x] . " = " . $arr[$x  ];
}    

But it does not work. The 2 elements of the variable have to be outputted within the same going through of the loop so I can't just concatenate them or something like that.

CodePudding user response:

Try a foreach loop and skip the odd numbers

foreach ($arr as $key => $value) {
    if($key % 2) continue;
    echo $arr[$key] . " = " . $arr[$key   1] . "\n";
}

This seems to produce the desired output

CodePudding user response:

Your array should look like this :

$arr = array("name"=> "john", "lastname"=> "doe", "age"=> 55);

and then you can go like this :

foreach ($arr as $key => $val) {
   echo $key , " = " , $val ;
}

CodePudding user response:

It just needs a couple of small adjustments:

for ($x = 0; $x < count($arr); $x =2) {
  echo $arr[$x] . " = " . $arr[$x 1] . "<br/>";
}
  1. Change the loop criteria so it'll get all the way to the end of the dataset.

  2. Change the loop criteria so it'll increment $x 2 steps at a time, and ten just get the 1 for the

  3. According to your question, it appears you want a line break between each data item. If this is for a web application, use <br/>. If it's for command-line or text-based output, use PHP_EOL.

However, there are other possible approaches using foreach which might be considered more elegant, as shown in the other answers here.


BTW, if you could have a more structured array using associative key-value pairs insteading of relying on index patterns e.g. array("name" => "john", "lastname" => "doe", "age" => 55); that would make your life easier in general, so if you have the freedom to make a change like that, I'd advise it.

  •  Tags:  
  • Related