Get keys from an associative array in PHP
Today we write a short article on how to get keys from an associative array in PHP.
array_keys() function, How to Get All the Keys of an Associative Array in PHP, How to loop through an associative array and get the key in PHP, How to get all keys out of associative array in php, how to get associative array key from numeric index, Php get keys from associative array, Print the keys of an array.
Checkout more articles on PHP
Way to get keys from an associative array
1. Using array_keys() function
The array_keys()
function returns the new array with keys. Let’s see one example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php $student_marks = array( "John"=>"89", "Michael"=>"79", "Christopher"=>"90", "Alexander"=> "81" ); $new_array = array_keys($student_marks); print_r($new_array); ?> // Output: Array ( [0] => John [1] => Michael [2] => Christopher [3] => Alexander ) |
2. Using foreach loop
We can also get all the keys from the array using the foreach loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php $student_marks = array( "John"=>"89", "Michael"=>"79", "Christopher"=>"90", "Alexander"=> "81" ); $new_userArray = array(); foreach($student_marks as $key=>$value){ echo $key . " : " . $value . "<br>"; } ?> // Output: John : 89 Michael : 79 Christopher : 90 Alexander : 81 |
That’s it for today.
Thank you for reading. Happy Coding!