Skip to content
Advertisement

Check if an array contains a specific value?

I’d like to check if there is a value on an array like this:

function check_value_new ($list, $message) {
    foreach ($list as $current) {
        if ($current == $message) return true;
    }
    return false;
}

function check_value_old ($list, $message) {
    for ($i = 0; $i < count ($status_list); $i ++) {
        if ($status_list[$i] == $$message) return true;
    }
    return false;
}

$arr = array ("hello", "good bye", "ciao", "buenas dias", "bon jour");
check_value_old ($arr, "buenas dias"); // works but it isn't the best
check_value_new ($arr, "buenas dias"); // argument error, where I'm wrong?

I’ve read the check_value_new method is a better way to work with arrays, but I’m not used to work with it, how I should fix it?

Advertisement

Answer

PHP offers a function called in_array that checks if a value exists in a given array.

You can change your check_value_new function to include this:

function check_value_new ($list, $message) {
   foreach ($list as $current) {
     if (in_array($message, $current)) {
            return true;
  }
   return false;
}

If you’d like to, you could also make the function work without the foreach loop, like so

function check_value_new ($list, $message) {
  // returns true if found, else returns false.
     return in_array($message, $list); 
 }
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement