+

PHP associative arrays

Example:
Here the array()function is used to create an associative array.
/ * The first way to create an associated array. * / $student_one = array ( "Maths" = > 95, "Physics" = > 90, "Chemistry" = > 96, "English" = > 93, "Computer" = > 98);  
/ * The second way to create an associated array. * / $student_two [ "Maths " ] = 95; $student_two [ "Physics" ] = 90; $student_two [ "Chemistry" ] = 96; $student_two [ "English" ] = 93; $student_two [ "Computer" ] = 98;  
/ * Direct access to elements * / echo "Marks for student one is:" ; echo "Maths:" . $student_two [ "Maths" ], "" ; echo "Physics:" . $student_two [ "Physics" ], "" ; echo "Chemistry:" . $student_two [ "Chemistry" ], "" ; echo "English:" . $student_one [ "English" ], "" ; echo "Computer:" . $student_one [ "Computer" ], "" ; ?>
Exit:
Marks for student one is: Maths: 95 Physics: 90 Chemistry: 96 English: 93 Computer: 98 
Traversing an associative array:
We can traverse associative arrays using loops. We can iterate over an associative array in two ways. First, using the for loopand secondly, using the foreach .Example:
Here the function array_keys ( )is used to find the index names given by it, and the function count()- to count the number of indices in associative arrays.  
/ * Create an associative array * / $student_one = array ( "Maths" = > 95, "Physics" = > 90, "Chemistry" = > 96, "English" = > 93, "Computer" = > 98);  
/ * Loop through the array using foreach * / echo "Looping using foreach: " ; foreach ( $student_one as $subject = > $marks ) { echo "Student one got" . $marks . "in" . $subject . "" ; }  
/ * Loop through the array using for * / echo "Looping using for: " ; $subject = array_keys ( $student_one ); $marks = count ( $student_one ); for ( $i = 0; $i < $marks ; ++ $i ) { echo $subject [ $i ]. `` . $student_one [ $subject [ $i ]]. "" ; }
?>
Exit:
Looping using foreach : Student one got 95 in Maths Student one got 90 in Physics Student one got 96 in Chemistry Student one got 93 in English Student one got 98 in Computer Looping using for: Maths 95 Physics 90 Chemistry 96 English 93 Computer 98 
< p> Create an associative array of mixed types
/ * Create an associative array of mixed types * / $arr [ "xyz" ] = 95; $arr [100] = " abc " ; $arr [11.25] = 100; $arr [ "abc" ] = "pqr" ;  
/ * Loop through the array using foreach * / foreach ( $arr as $key = > $val ) { echo $key . "== >" . $val . " " ; }
?>
Exit:
xyz == > 95 100 == > abc 11 == > 100 abc == > pqr 
Get Solution for free from DataCamp guru