Question

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.

Was it helpful?

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;
    }
}

OTHER TIPS

You can change your function to the following:

function getDescription($uri) {
    if (isset($descriptionArr[$uri])) {
      return $descriptionArr[$uri];
    } else {
      return false;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top