Home > database >  Printing Arrays with different names using for and foreach in php
Printing Arrays with different names using for and foreach in php

Time:09-25

new to php and wanted to know if there was an easy way to fix this problem.

$class_1 = array("Name" => "Lule", "Surname" => "Mirela", "Email" => "[email protected]", "Birthday" => "30/04/2001");
$class_2 = array("Name" => "Aida", "Surname" => "Besim", "Email" => "[email protected]", "Birthday" => "16/11/2001");
$class_3 = array("Name" => "Flaka", "Surname" => "Agim", "Email" => "[email protected]", "Birthday" => "23/09/2003");
for($i = 1; $i <= 3; $i  ) {
    foreach ($class_1 as $key => $val) {
        echo $key. ": ";
        echo $val. "<br/>";
    }
}```

Technically i thought it would be possible to just write "$class_$i" but that doesnt seem to work. I am not familiar with php syntax.

CodePudding user response:

Try using multidimensional Arrays. Something like this.


$class[0] = array("Name" => "Lule", "Surname" => "Mirela", "Email" => "[email protected]", "Birthday" => "30/04/2001");
$class[1] = array("Name" => "Aida", "Surname" => "Besim", "Email" => "[email protected]", "Birthday" => "16/11/2001");
$class[2] = array("Name" => "Flaka", "Surname" => "Agim", "Email" => "[email protected]", "Birthday" => "23/09/2003");
for($i = 0; $i <= 2; $i  ) {
    foreach ($class[$i] as $key => $val) {
        echo $key. ": ";
        echo $val. "<br/>";
    }
}

Also fyi, having class as a variable name is a terrible idea.

CodePudding user response:

What you are looking for are called "variable variables". You have to build a variable which contains the array name and use it with the double dollar sign:

$class_1 = array("Name" => "Lule", "Surname" => "Mirela", "Email" => "[email protected]", "Birthday" => "30/04/2001");
$class_2 = array("Name" => "Aida", "Surname" => "Besim", "Email" => "[email protected]", "Birthday" => "16/11/2001");
$class_3 = array("Name" => "Flaka", "Surname" => "Agim", "Email" => "[email protected]", "Birthday" => "23/09/2003");
for($i = 1; $i <= 3; $i  ) {
    $array = "class_$i";
    foreach ($$array as $key => $val) {
        echo $key. ": ";
        echo $val. "<br/>";
    }
}

Or more concisely:

$class_1 = array("Name" => "Lule", "Surname" => "Mirela", "Email" => "[email protected]", "Birthday" => "30/04/2001");
$class_2 = array("Name" => "Aida", "Surname" => "Besim", "Email" => "[email protected]", "Birthday" => "16/11/2001");
$class_3 = array("Name" => "Flaka", "Surname" => "Agim", "Email" => "[email protected]", "Birthday" => "23/09/2003");
for($i = 1; $i <= 3; $i  ) {
    foreach (${"class_$i"} as $key => $val) {
        echo $key. ": ";
        echo $val. "<br/>";
    }
}

However in my opinion making an array as suggested by @Akshay Pose is generally better.

  • Related