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

How to delete PHP array element key value and reorder

藏色散人
Release: 2019-01-18 09:05:20
Original
16011 people have browsed it

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);
Copy after login

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
Copy after login

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
Copy after login

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!

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