Search code examples
phparraysarray-key-exists

"array_key_exists()" not working properly


Code

$descriptionArr = array( "uk/page"=>"", "uk/page-two"=>"description of page 2");

function getDescription($uri){
    if (array_key_exists($uri, $descriptionArr)) {
      return $descriptionArr[$uri];
    } else {
      return false;
    }
}

Situation

  • When i call the function with argument "uk/page-two" it returns the description
  • When I call the function with argument "uk/page" it returns false instead of the empty string

Issue

I would like it to return the empty string and only return false when the argument passed does not exist as key in the array.


Solution

  • This should work:

    $descriptionArr = array( "uk/page"=>"", "uk/page-two"=>"description of page 2");
    
    function getDescription($uri, $descriptionArr){
        if (false !== array_key_exists($uri, $descriptionArr)) {
          return $descriptionArr[$uri];
        } else {
          return false;
        }
    }