Remove keys from an associative array in PHP
📅October 9, 2020
🗁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:
array_values(array)
Parameter:
It required only a single parameter that specifies the array. Refer to the following example.
Example:
<!--?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.
<!--?php<p-->
$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..!!