note 92598 deleted from function.array-search by thiago
| From: | thiago@php.net | Date: | Fri, 31 Jul 2009 12:56:41 +0000 |
| Subject: | note 92598 deleted from function.array-search by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158951@lists.php.net to get a copy of this message | ||
Note Submitter: reeve dot farmer at yahoo dot com
----
re: greenmr:
"Some solutions I've seen here and elsewhere return the index of the found element on a
match, and "false" on a fail. Since PHP treats a zero the same as false in expressions,
and zero is a valid array index, using false to designate "not found" gives an ambiguous
result in some cases. I chose to use the value -1 to signify a search failure instead."
You can cope with the 0/false ambiguity simply by making sure to do type-safe comparisons with ===
and !==.
e.g.:
<?php
if(($i = binarySearch($array)) !== false) {
//we had a match
}
?>
This is how some PHP functions like array_search() work (if you look at the doc for array_search(),
there's a warning to make sure to use the same comparison operators). The contributors you
refer to were likely modeling their functions on that example.