Home  >  Article  >  Backend Development  >  How to remove keys from array in php

How to remove keys from array in php

PHPz
PHPzOriginal
2023-04-23 10:22:01671browse

PHP is a widely used scripting language that occupies an important position in Web development. In PHP, array is a common data structure that can store multiple variables of the same type. However, sometimes we need to remove the keys in the array in the program and keep only the data values. So, how to achieve it? This article will detail how to remove keys from an array in PHP.

1. array_values() function

PHP provides an array_values() function that can remove the keys in the array and retain only the data values. The function of this function is to return a new array, and the indexes in the new array are consecutive integers. The sample code is as follows:

$arr1 = array(
    'one' => '1',
    'two' => '2',
    'three' => '3'
);
$arr2 = array_values($arr1);
print_r($arr2);

After executing this code, the output result is:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

As you can see, through the array_values() function, we successfully removed the keys in the original array $arr1.

2. Unset function

In addition to using the array_values() function, we can also use the unset function to delete the keys of an array. The unset function is a built-in function in PHP that deletes variables, including keys in an array. The following is a sample code:

$arr1 = array(
    'one' => '1',
    'two' => '2',
    'three' => '3'
);
foreach($arr1 as $key => $value) {
    unset($arr1[$key]);
}
print_r($arr1);

After executing this code, the output result is:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

As you can see, our code successfully deleted all keys in the original array, leaving only data value.

Thinking:

The array_values ​​function is implemented by taking out the KEY and redistributing the index, while unset is achieved by directly deleting the key value. The difference is quite obvious.

The above is the detailed content of How to remove keys from 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