note 119799 added to language.types.boolean
| From: | goran77 at fastmail dot fm | Date: | Mon, 29 Aug 2016 06:48:15 +0000 |
| Subject: | note 119799 added to language.types.boolean | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-206413@lists.php.net to get a copy of this message | ||
Just something that will probably save time for many new developers: beware of interpreting FALSE
and TRUE as integers.
For example, a small function for deleting elements of an array may give unexpected results if you
are not fully aware of what happens:
<?php
function remove_element($element, $array)
{
//array_search returns index of element, and FALSE if nothing is found
$index = array_search($element, $array);
unset ($array[$index]);
return $array;
}
// this will remove element 'A'
$array = ['A', 'B', 'C'];
$array = remove_element('A', $array);
//but any non-existent element will also remove 'A'!
$array = ['A', 'B', 'C'];
$array = remove_element('X', $array);
?>
The problem here is, although array_search returns boolean false when it doesn't find specific
element, it is interpreted as zero when used as array index.
So you have to explicitly check for FALSE, otherwise you'll probably loose some elements:
<?php
//correct
function remove_element($element, $array)
{
$index = array_search($element, $array);
if ($index !== FALSE)
{
unset ($array[$index]);
}
return $array;
}
----
Server IP: 72.52.91.14
Probable Submitter: 95.178.196.210
----
Manual Page -- http://php.net/manual/en/language.types.boolean.php
Edit -- https://master.php.net/note/edit/119799
Del: integrated -- https://master.php.net/note/delete/119799/integrated
Del: useless -- https://master.php.net/note/delete/119799/useless
Del: bad code -- https://master.php.net/note/delete/119799/bad+code
Del: spam -- https://master.php.net/note/delete/119799/spam
Del: non-english -- https://master.php.net/note/delete/119799/non-english
Del: in docs -- https://master.php.net/note/delete/119799/in+docs
Del: other reasons-- https://master.php.net/note/delete/119799
Reject -- https://master.php.net/note/reject/119799
Search -- https://master.php.net/manage/user-notes.php