Home >Backend Development >PHP Problem >php remove array key
In PHP development, we often need to store and process data through arrays. Sometimes we need to remove the keys in the array and keep only the values. In this case, we need to use some methods to process the array.
Although array key-value pairs are a very common data structure in PHP, sometimes it is very useful to remove the keys in the array. Common situations include:
Sometimes we need to find data based on the value in the array instead of looking for the key. This works well if the keys of the array are automatically generated numbers.
If we want to count the values in the array without caring about the keys, removing the keys from the array is a good choice.
When performing database query, sometimes we only need to query some specific fields instead of the entire record. At this time, it is very practical to remove the keys from the array.
So, how to remove the keys of the array in PHP? Below we introduce several methods.
Method 1: array_values()
The array_values() function in PHP will return a new array composed of the values of the array, and the key names remain unchanged. The function of this function is to remove the keys from the array and keep only the values. The example is as follows:
$arr = array('one'=>'1', 'two'=>'2', 'three'=>'3'); $new_arr = array_values($arr); print_r($new_arr);
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 )
Method 2: array_map()
array_map() function is to apply the callback function to each value in the array , and returns a new array. This callback function can be any user-defined function, or it can be a function that comes with PHP. We can use this function to remove the keys of the array. The example is as follows:
$arr = array('one'=>'1', 'two'=>'2', 'three'=>'3'); $new_arr = array_map(function($value){ return $value; }, $arr); print_r($new_arr);
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 )
Method 3: foreach loop
If we don’t want to use PHP’s built-in function, You can use a simple foreach loop to solve this problem. The example is as follows:
$arr = array('one'=>'1', 'two'=>'2', 'three'=>'3'); $new_arr = array(); foreach($arr as $value){ $new_arr[] = $value; } print_r($new_arr);
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 )
Of course, if you only care about the values in the array and not the keys, you can also When creating an array, directly create an array of values.
$values = array(1, 2, 3);
Through the above method, we can easily remove the keys of the array in PHP and keep only the values. This is also very commonly used in real-world development, especially when dealing with data and statistics.
The above is the detailed content of php remove array key. For more information, please follow other related articles on the PHP Chinese website!