Home > other >  Using Foreach to echo array in an array
Using Foreach to echo array in an array

Time:10-30

I want to echo each persona included in the array $personas.

The following code echoes the first persona but it doesn't breaks the line and displays the second ("Mike").

Any help is much appreciated :)

<?php
$personas = array(
        $persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
        $persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
    );


foreach ($personas as $persona ) {
    foreach ( $person as $inner_param => $inner_value ) {

    echo $param . ": " . $value . "<br>";
    
    }


  };
?>

Desired result:

Name: John | Age: 30 | Nationality: Spain |

Name: Mike | Age: 45 | Nationality: Peru |

CodePudding user response:

I believe that I fixed it. Should it be as follows? Any better option?

foreach ($personas as $persona ) {

    echo "<br>";
    foreach ( $persona as $param => $value ) {

    echo $param . ": " . $value . " | ";
    
    }
};

CodePudding user response:

Try this;

$personas = array(
    $persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
    $persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);

foreach ($personas as $persona ) {
$text = "";
foreach ( $persona as $key => $val ) {
  $text .= $key . ": " . $val . ' | ';
}
echo $text .'<br>';
}
  •  Tags:  
  • php
  • Related