문제

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?

도움이 되었습니까?

해결책 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

다른 팁

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) { }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top