Displaying elements of an array by looping

$a= array("Three", "two", "Four", "five","ten");
foreach($a as $key => $val) {
echo "$key -> $val <br>";
0 -> Three
1 -> two
2 -> Four
3 -> five
4 -> ten
We can loop through an array to display each element of the array.  This code will display all the element of an array. This is very useful in many occasions where a list is to be displayed. We will see the application of this in check box value collection.

First we will create an array and then display each element of it.

Creating Array in PHP using Key & values and displaying elements by index position and by looping

Here is the code to create  and  display the value of the elements of an array.

Using sizeof function to display all elements using for loop

$a= array("Three", "two", "Four", "five","ten"); 
for($i=0; $i<$max; $i++) { 
echo "$a[$i] ,"; 

Displaying one element

By using key or by index we can display one element at a time. Here is the code.
$a= array("Three", "two", "Four", "five","ten"); 
echo $a[2]; // Output is Four
Using Key
echo $mark[Alex]; // Output is 48

Using while loop

$a= array("Three", "two", "Four", "five","ten"); 
while($i < count($a)){
echo $a[$i];
echo '<br>';	
Instead of checking $i value against count($a) in each iteration we can fix the value.
$a= array("Three", "two", "Four", "five","ten"); 
while($i < $total){
echo $a[$i];
echo '<br>';	
More on PHP while loop

Using print_r

We can use print_r funciton which returns variables in human readable format. Here is the code.
$a= array("Three", "two", "Four", "five","ten"); 
The output of the above code is here.
Array ( [0] => Three [1] => two [2] => Four [3] => five [4] => ten ) 
Same way here is one more array
$ar=array("FName"=>"John","Address"=>"Streen No 11 ","City"=>"Rain Town","Country"=>"USA");
The output is here
Array ( [FName] => John [Address] => Streen No 11 [City] => Rain Town [Country] => USA ) 
There are other way like using foreach function to display the elements of an array
$ar=array("FName"=>"John","Address"=>"Streen No 11 ",
	"City"=>"Rain Town","Country"=>"USA");
foreach($ar as $key => $val) {
echo "$key -> $val <br>";
FName -> John
Address -> Streen No 11
City -> Rain Town
Country -> USA
Creating Array
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net




    how to get only key and key => values of Multidimensional Arrays ? like this way 1=>a,2=>b,3=>c answer= 1,2,3 and another one 1-A=>1,2,3 2-B=>1,2 means here a1 is array then A is also array under 1 and 1,3,2 is value of A. so i want this like that way.

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer