Conceptually what happens to a php array if all its elements are unset?

153 Views Asked by At

Conceptually what happens to an array that has all of its elements unset? Please see the below code for and example:

$ourArray = array(
    "1",
    "2",
    "3",
    "4"
);

foreach($ourArray as $key => $value){
    unset($ourArray[$key])
}

In this case is the entire array considered unset? Or is the array considered empty?

Would $ourArray == array() or null?

5

There are 5 best solutions below

1
Shankar Narayana Damodaran On BEST ANSWER

In this case is the entire array considered unset?

No

Or is the array considered empty?

Yes

By the way you can try out your own example with these testcases

<?php

echo isset($ourArray)?1:0; // "prints" 0 since array doesn't contain anything
echo empty($ourArray)?1:0; // "prints" 1 since elements are not there !

$ourArray = array(
    "1",
    "2",
    "3",
    "4"
);
echo empty($ourArray)?1:0; // "prints" 0 since elements are there !

foreach($ourArray as $key => $value){
    unset($ourArray[$key]);
}

echo isset($ourArray)?1:0; // "prints" 1 since the array is set , only the elements are emptied
echo empty($ourArray)?1:0; // "prints" 1 since the array elements are empty
0
Eisa Adil On

The keys are not shuffled or renumbered. The unset() key is simply removed and the others remain. So the array still exists, only the element gets deleted. Yes, and the array will remain.

0
MaGnetas On

It should be an array without any values in it. So technically it's the same as array()

0
Nambi On
<?php
  $ourArray = array(
    "1",
    "2",
    "3",
    "4"
);

foreach($ourArray as $key => $value){
    unset($ourArray[$key]);
}
var_dump($ourArray);

?>

output

array(0) { }
0
iivannov On

The unset() method destroys the variable passed. So passing all the array keys unset() destroys them (not the array) and leaves the actual array empty.

1. Unsetting all the elements

So doing this will result in an empty $array

foreach ($array as $k => $value)
    unset($array[$k];

var_dump($array) //array {}

2. Unsetting the whole array

However passing the whole array to the unset() method will destroy the whole array and will will result in $array to be NULL

unset($array)

var_dump($array) // NULL