How to re-index deleted elements in php array, php array element index_PHP tutorial

WBOY
Release: 2016-07-13 10:18:54
Original
951 people have browsed it

How to re-index deleted elements in php array, php array element index

If you want to delete an element in an array, you can directly use unset, but what I saw today surprised me

Copy code The code is as follows:

$arr = array('a','b','c','d');
unset($arr[1]);
print_r($arr);
?>

After print_r($arr), the result is not like that. The final result is Array ( [0] => a [2] => c [3] => d )

So how can the missing elements be filled and the array re-indexed? The answer is

array_splice():

Copy code The code is as follows:

$arr = array('a','b','c','d');
array_splice($arr,1,1);
print_r($arr);
?>

After print_r($arr), the result is A(www.jb51.net)rray ( [0] => a [1] => c [2] => d )

Delete the specified element from the array

array_search() is more practical

The array_search() function is the same as in_array(), searching for a key value in the array. If the value is found, the key of the matching element is returned. If not found, return false

Copy code The code is as follows:

$array = array('1', '2', '3', '4', '5');
$del_value = 3;
unset($array[array_search($del_value, $array)]);//Use unset to delete this element
print_r($array);

Output
array('1', '2', '4', '5');

But if you want to re-index the array, you need to use foreach to traverse the deleted array and then re-create an array. This is also possible.

How to delete the array key value in php and turn it into an index array

array_values() returns all the values ​​in the input array and indexes them numerically.

array_value($arr['date']);

After php deletes a specified item in the two-dimensional array, the index is still arranged in order?

Solution 1: Create a new array:

$newArr = array();

foreach($arr as $key=>$value){
$newArr[] = $value ;

}

Solution 2: Sort
sort($arr);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/879723.htmlTechArticleRe-indexing method to delete elements in php array, php array element index if you want to delete an element in an array Elements can be used directly with unset, but what I saw today really surprised me...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template