Home  >  Article  >  Backend Development  >  The difference between unset and array_splice in deleting elements in an array in PHP, unsetarray_splice_PHP tutorial

The difference between unset and array_splice in deleting elements in an array in PHP, unsetarray_splice_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:22:07766browse

The difference between unset and array_splice in PHP to delete elements in an array, unsetarray_splice

If you want to delete an element in an array, you can use unset directly, but the index of the array will not be rearranged:

<&#63;php 
$arr = array('a','b','c','d');
unset($arr[1]);
print_r($arr);
&#63;>


The result is:

Array ( [0] => a [2] => c [3] => d )

So how can we ensure that missing elements are filled in and the array is re-indexed? The answer is array_splice():

<&#63;php 
$arr = array('a','b','c','d'); 
array_splice($arr,1,1); 
print_r($arr); 
&#63;>

The result is:

Array ( [0] => a [1] => c [2] => d )

Delete specific elements in the array

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

Supplementary deletion of empty arrays

Example:

<&#63;php
  $array = ('a' => "abc", 'b' => "bcd",'c' =>"cde",'d' =>"def",'e'=>"");
  array_filter($array);
  echo "<pre class="brush:php;toolbar:false">";
  print_r($array);
&#63;>


Result:

Array (
[a] => abc
[b] => bcd
[c] => cde
[d] => def
)

Summary

If the array_splice() function is deleted, the index value of the array will also change.
If the unset() function deletes it, the index value of the array will not change.

What is the difference between unset and array_pop in php?

unset can delete all variables. array_pop only operates on arrays and only pops the last element of the array. unset can delete any element in the array

php delete elements in array

I don’t know. Do you know the array_slice function?
$arr = array_slice($arr, 0, 3);
That’s it.
array_slice() The first parameter is the array to be cut, the second parameter is the starting position, and the third parameter is the length.
It is to cut the $arr array and count 3 elements from the 0th element downwards.
array_slice is very flexible in usage and can support negative parameters. You can check the PHP manual for details.
cn.php.net/manual/en/function.range.php

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/851336.htmlTechArticleThe difference between unset and array_splice in PHP to delete elements in an array. unsetarray_splice If you want to delete an element in an array, You can use unset directly, but the index of the array will not be rearranged...
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