Home  >  Article  >  Daily Programming  >  How to delete PHP array element key value and reorder

How to delete PHP array element key value and reorder

藏色散人
藏色散人Original
2019-01-16 14:06:2715776browse

I want to delete the key value of an element in the PHP array and then re-standardize the index sorting. We can use the built-in functions unset() and array_values() in PHP to achieve this.

How to delete PHP array element key value and reorder

# Below we will combine simple code examples to introduce to you how to delete the key values ​​​​of PHP array elements and reorder them.

The code example is as follows:

<?php

//删除数组元素键值重新排序

$x = array(1,2,3,4,5);
var_dump($x);

unset($x[3]);
$x = array_values($x);

var_dump($x);

In this code, we print the array $x before deleting the $x[3] element, after deletion without reordering, and after deletion. Sorted results.

The sorting comparison is shown in the figure below:

How to delete PHP array element key value and reorder

As shown in the figure, we use array_values() to re-index the array after deleting elements.

Related function introduction:

unset: Release the given variable

unset ( mixed $var [, mixed $... ] ) : void

unset() Destroy the specified Variables. The behavior within the function will vary depending on the type of variable you want to destroy.

If you unset() a global variable in a function, only the local variable will be destroyed, and the variables in the calling environment will maintain the same value before calling unset().

array_values: Returns all the values ​​in the array

array_values ( array $array ) : array

array_values() Returns all the values ​​in the input array and creates a numerical index for them.

Parameter array array. Return value, returns the index array containing all values.

This article is an introduction to the method of deleting and reordering the key values ​​of PHP array elements. It is simple and easy to understand. It is also one of the common PHP interview questions. I hope it will be helpful to friends in need!


The above is the detailed content of How to delete PHP array element key value and reorder. 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