PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] Why is array_search not finding, unless array is sorted?

 July 22, 2022     php, php-5.4     No comments   

Issue

I'm having trouble understanding the result of array_search in the following example (and did not find any existing questions discussing this):

<?php

    $values = array(
        15,
        12,
        "15",
        34,
        15 => 25,
        "xx" => 15
    );
    echo "PHP-Version is " . phpversion();
    echo "<h1>Array:</h1><pre>";var_dump($values);echo "</pre>";    

    // sort($values); // remove comment and 15 will be found in ALL cases!

    $key = array_search("15",$values);
        show_result('(a) Searching "15"');

    $key = array_search("15",$values,true);
        show_result('(b) Searching "15",true');

    $key = array_search(15,$values);
        show_result('(c) Searching 15');

    $key = array_search(15,$values,false);
        show_result('(d) Searching 15,false');

    $key = array_search(15,$values,true);
        show_result('(e) Searching 15,true');



function show_result($tit) {    
    global $key,$values;
    echo "<h2>$tit</h2>";

    if (!$key) { 
        echo "Not found";
        } else {
            echo "Found key $key - " . gettype($values[$key]);
    }
}
?>

Only search (b) - the strict string-search finds the value, numeric search does not find it. All searches do find it when the array is sorted - but the doc does not mention such a requirement at all. Can someone explain this behaviour?


Solution

The value 15 is at key 0. array_search returns this 0. 0 evaluates to false. Your check if (!$key) therefore fails for the key 0. You have to check for strict === false. There's a giant red warning in the manual explaining this.



Answered By - deceze
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing