Frage

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?

War es hilfreich?

Lösung 2

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

Andere Tipps

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

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.

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

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

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

?>

output

array(0) { }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top