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.
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.
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.
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.
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).
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 )
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 )
They are as they were. That one key is JUST DELETED
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
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With