Remove keys from an associative array in PHP
Today we’ll write a short article on how to remove keys from an associative array in PHP and get an array without keys to return a new reindex array which starts with index 0.
Refer the article to get keys from an associative array in PHP.
Ways to remove keys from associative array
1. Using built-in function
We have built-in array_values() function to remove the keys and re-create the array with new keys starting from 0. It returns an indexed array of values.
Syntax:
1 | array_values(array) |
Parameter:
It required only a single parameter that specifies the array. Refer to the following example.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php $userArray = array( "John"=>"John", "Michael"=>"Michael", "Christopher"=>"Christopher", "Alexander"=> "Alexander", "Samuel"=> "Samuel", ); $new_userArray = array_values($userArray); print_r($new_userArray); ?> // Output: Array ( [0] => John [1] => Michael [2] => Christopher [3] => Alexander [4] => Samuel ) |
2. Using custom function
We can also remove the keys and get an array values using foreach loop with custom function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php $userArray = array( "John"=>"John", "Michael"=>"Michael", "Christopher"=>"Christopher", "Alexander"=> "Alexander", "Samuel"=> "Samuel", ); $new_userArray = array(); foreach($userArray as $user){ $new_userArray[] = $user; } print_r($new_userArray); ?> // Output: Array ( [0] => John [1] => Michael [2] => Christopher [3] => Alexander [4] => Samuel ) |
That’s it for today.
Thank you for reading. Happy Coding..!!