Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Unset Array value effect on other indexes

Tags:

arrays

php

unset

I am working with a PHP loop, and I had one question regarding how unset affects the array keys. This array uses the standard numeric keys assigned by PHP, 0, 1, 2, 3 etc.... Whenever unset() runs on an array value, are the array keys shuffled or are they maintained as before?

Thank you for your time.

like image 716
Oliver Spryn Avatar asked Jun 16 '11 18:06

Oliver Spryn


People also ask

What happens when you use unset () to remove a value from an array?

The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array. After removal the associated key and value does not change.

How do you unset an array element in PHP?

In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically. Function Used: unset(): This function unsets a given variable.

How does PHP unset work?

unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed.

What does Array_splice () function do?

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).


4 Answers

The keys are not shuffled or renumbered. The unset() key is simply removed and the others remain.

$a = array(1,2,3,4,5); unset($a[2]); print_r($a);  Array (     [0] => 1     [1] => 2     [3] => 4     [4] => 5 ) 
like image 74
Michael Berkowski Avatar answered Sep 20 '22 09:09

Michael Berkowski


Test it yourself, but here's the output.

php -r '$a=array("a","b","c"); print_r($a); unset($a[1]); print_r($a);' Array (     [0] => a     [1] => b     [2] => c ) Array (     [0] => a     [2] => c ) 
like image 31
Glen Solsberry Avatar answered Sep 21 '22 09:09

Glen Solsberry


They are as they were. That one key is JUST DELETED

like image 20
genesis Avatar answered Sep 21 '22 09:09

genesis


The Key Disappears, whether it is numeric or not. Try out the test script below.

<?php
    $t = array( 'a', 'b', 'c', 'd' );
    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 1: b, 2: c, 3: d

    unset($t[1]);

    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 2: c, 3: d
?>
like image 21
Jeff Lambert Avatar answered Sep 20 '22 09:09

Jeff Lambert