-2

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.

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
skrln
  • 542
  • 2
  • 8
  • 19

2 Answers2

2

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;
    }
}
ek9
  • 3,392
  • 5
  • 23
  • 34
  • This wouldn't, because `$descriptionArr` is not available inside the function. – Amal Murali Apr 17 '14 at 07:45
  • It works, I do have the array within the function, so that isn't the issue. Can someone explain what the `false !== array_key_...` does exactly? – skrln Apr 17 '14 at 07:49
  • the `===` (and `!==`) disallow type conversion. See http://stackoverflow.com/questions/589549/php-vs-operator – ek9 Apr 17 '14 at 07:52
  • The function already returns a Boolean, so the explicit !== is redundant. – Ja͢ck Apr 18 '14 at 02:52
0

You can change your function to the following:

function getDescription($uri) {
    if (isset($descriptionArr[$uri])) {
      return $descriptionArr[$uri];
    } else {
      return false;
    }
}
Go0se
  • 98
  • 1
  • 8