Home  >  Article  >  Backend Development  >  How to distinguish the difference between unset and array_splice in PHP

How to distinguish the difference between unset and array_splice in PHP

autoload
autoloadOriginal
2021-04-01 14:43:521857browse

How to distinguish the difference between unset and array_splice in PHP

1. Function used

a. Function unset()

unset ( mixed $var , mixed $... = ? ) : void

          unset() Destroy the specified variable.

b. Functionarray_slice()

  array_splice(array,start,length,array)
  • Array represents an array.

  • start indicates the starting position of deleted elements.

  • length represents the number of elements removed and is also the length of the returned array. (Optional)

  • array represents an array with elements to be inserted into the original array (Optional)

2. Example:

Use unset() to delete an element in the array

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

Output:

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

Use array_splice()Delete an element in the array

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

​​ Output:

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

Recommendation: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of How to distinguish the difference between unset and array_splice 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