Home >Backend Development >PHP Problem >How to delete array elements and reorder them in php

How to delete array elements and reorder them in php

青灯夜游
青灯夜游Original
2021-03-16 18:01:145515browse

php method to delete array elements and reorder: first use the unset() function to delete the specified element in the array; then use the array_values() function to reorder. The array_values() function can reset the array information, and the key values ​​of the array will be rearranged starting from 0.

How to delete array elements and reorder them in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php deletes array elements and reorders them

<?php
$arr1 = array(1,3, 5,7,8);
var_dump($arr1);
foreach ($arr1 as $key=>$value)
{
  if ($value === 3)
    unset($arr1[$key]);
}
$arr2 =array_values($arr1);
var_dump($arr2);
?>

Output:

array (size=5)
  0 => int 1
  1 => int 3
  2 => int 5
  3 => int 7
  4 => int 8
  
array (size=4)
  0 => int 1
  1 => int 5
  2 => int 7
  3 => int 8

Related function introduction:

unset: Release the given variable

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

unset() Destroys the specified variable. 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, return the index array containing all values.

Tip: The returned array will use numeric keys, starting at 0 and increasing by 1.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete array elements and reorder them 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