www.retosphere.de

Array_search does not find first element

Home
Projects
News
Links
GuestBook
Contact
Tnx to Dominic, who told me the following foolish bug:

You can use array_search for searching for elements in arrays.
 
<?php
$array 
= array("first""second""third");
foreach (
$array as $value)
    echo 
"value in array: $value<br>";

echo 
"searching for element 'second':<br>";
    
if (
$found array_search("second"$array))
    echo 
"FOUND!<br>";
else echo 
"<b>NOT FOUND!</b><br>";
?>
That's how you do it. And it works fine as long as you try to find an element somewhere in the array, not the first element.
show me
 
 
<?php
$array 
= array("first""second""third");
foreach (
$array as $value)
    echo 
"value in array: $value<br>";

echo 
"searching for element 'first':<br>";

if (
$found array_search("first"$array))
    echo 
"FOUND!<br>";
else echo 
"<b>NOT FOUND! 'first' does not seem to be in the array, as it could not be found...</b><br>";
?>
But looking for the first element does not work.
show me


Today (7.12.2005), a reader sent in the solution (thanks to phazei):
 
 
<?php
    $array 
= array("first""second""third");
    foreach (
$array as $value)
        echo 
"value in array: $value<br>";
    
    echo 
"searching for element 'first':<br>";
    
    if (
FALSE !== array_search("first"$array)) 
    {
        echo 
"FOUND!<br>";
    } 
    else echo 
"<b>NOT FOUND! 'first' does not seem to be in the array, as it could not be found...</b><br>";
?>
show me
It shows again, that weak typing and internal typing produce the need for new operators such as '===' and '!==' ...


Top
this page last updated: 07.12.2005
Top