0
How can I able to see only one array elements in multidimensional array using foreach() loop in Php?
Hello guys, I am learning php. I have learned about foreach loop that is only for array. Now I am little bit confused how can I only see the asia array elements? I have tried foreach ($continents as $subcontinents){ print $subcontinents[0].'<br/>'; } this one but it is getting the first element of every array. Thanks in advance. https://code.sololearn.com/wyrWNTYJ26wN/?ref=app
4 odpowiedzi
+ 1
Try this:
echo implode(', ', $continents["Asia"]);
+ 1
To be honest, I'm not particularly au fait with PHP, but it makes sense to me that the foreach loop iterates over the associated array (in your case $continents) and takes the value (of each key) each time. So on the first iteration, $subcontinents takes on the value of your "Asia" array (i.e. ("Bangladesh", "India", "Pakistan")), then the "Europe" array second time around and the "Africa" array last.
Where you had $suncontinents[0] within the loop, this printed the first element of the array each time around.
$continents[0] would not return the array set as "Asia", even though it was the first key: value pair listed, because there is no inherent order with an associated array. You would retrieve the "Asia" array using $continents["Asia"].
Unfortunately, simply using the statement
echo $continents["Asia"];
would not print the array as required and it needs the implode() method for it to be printed as you need.
Hope that makes sense to you.
0
Thanks, Russ. It's working. But would you please explain in short how it works? It will be great for me as I am a beginner.
0
thank u dear. I got it.