I would like to echo a bunch of arrays in numerical order, I tried using WHILE method but lacks the knowledge on how to combine strings to call a variable and get the value inside the array.
$ins1 = array (
"select" => array (
"1" => "1"
),
"note" => array (
"1" => "Message"
)
);
$ins2 = array (
"select" => array (
"1" => "2"
),
"note" => array (
"1" => "Sorry"
)
);
$count = 1;
while($count <= 2){
$ins = '$ins'.$count;
echo $ins["select"][$count] .' '. $ins["note"][$count].'<br>';
$count++;
}
OUTPUT SHOULD BE:
1 Message
2 Sorry
What you're looking for is "Variable variables", through which you can set the variable name dynamically; so to get what you want, change your code as the following:
$count = 1;
while($count <= 2){
$ins = 'ins'.$count;
$var = $$ins; // now your $var is either $ins1 or $ins2 :)
echo $var["select"][1] .' '. $var["note"][1].'<br>';
$count++;
}
The output would be:
1 Message
2 Sorry
this will do the trick for you:
$ins1 = array (
"select" => array (
"1" => "1"
),
"note" => array (
"1" => "Message"
)
);
$ins2 = array (
"select" => array (
"1" => "2"
),
"note" => array (
"1" => "Sorry"
)
);
for($i=1; $i<1000; $i++) {
$arr_name = 'ins'.$i;
if(isset($$arr_name)) {
$str = '';
foreach ($$arr_name as $key => $value) {
$str .= $value[1].' ';
}
echo trim($str).'<br/>';
} else {
break;
}
}
Note: I have taken 1000 as a highest possible value, you can change accordingly. like in your case it is 2.
You should have combined the two variable, and make life easier:
$ins = [
[//$ins1
"select" => array ("1" => "1"),
"note" => array ("1" => "Message" )
],
[//$ins2
"select" => array ("1" => "2"),
"note" => array ("1" => "Sorry")
]
];
for ($i = 0; $i < count($ins); $i++)
{
echo $ins[$i]["select"][1]." ".$ins[$i]["note"][1]."<br/>";
}
for dynamic name of variables, see other answers.. hope i've helped you.. Cheers! ;)