Home  >  Article  >  Backend Development  >  How to remove the key value of an array in PHP

How to remove the key value of an array in PHP

PHPz
PHPzOriginal
2023-04-20 15:06:58748browse

In PHP, sometimes it is necessary to remove the key values ​​​​in the array, leaving only the value. This article will introduce how to use PHP built-in functions to achieve this function.

1. Use the array_values() function

The array_values() function can return all the values ​​in the array and re-index. For example:

$arr = array('one' => 'PHP', 'two' => 'JAVA', 'three' => 'Python');
$new_arr = array_values($arr);
print_r($new_arr);

Output result:

Array ( [0] => PHP [1] => JAVA [2] => Python )

You can see that the key values ​​in the new array have been removed, leaving only the values.

2. Use foreach loop

We can also use foreach loop to remove the array key value. For example:

$arr = array('one' => 'PHP', 'two' => 'JAVA', 'three' => 'Python');
$new_arr = array();
foreach ($arr as $value) {
    $new_arr[] = $value;
}
print_r($new_arr);

Output result:

Array ( [0] => PHP [1] => JAVA [2] => Python )

You can also see that the key values ​​in the new array have been removed, leaving only the values.

3. Use the array_map() function

The array_map() function can perform the same operation on one or more arrays. We can use an anonymous function to retrieve the value of the array. For example:

$arr = array('one' => 'PHP', 'two' => 'JAVA', 'three' => 'Python');
$new_arr = array_map(function($value) {
    return $value;
}, $arr);
print_r($new_arr);

Output result:

Array ( [one] => PHP [two] => JAVA [three] => Python )

It can be seen that after using the anonymous function, the key values ​​​​in the new array have not been removed. However, we can remove these keys again by using the array_values() function.

Summary:

This article introduces three methods to remove key values ​​​​in PHP arrays, leaving only the values. Among them, using the array_values() function is the simplest and most straightforward, using the foreach loop is more flexible, and using the array_map() function is more advanced. Depending on actual needs, we can choose different methods to solve the problem.

The above is the detailed content of How to remove the key value of an array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn