iDev
iDev

Reputation: 2433

PHP: check if an element belongs to an array

I know PHP 4 and PHP 5 supports a built in function in_array for determining is an element is in an array or not.

But, I am using a prior version of PHP for some reason and wanted to know what is the alternative for it.

Upvotes: 1

Views: 359

Answers (5)

dev-null-dweller
dev-null-dweller

Reputation: 29482

If you are using something older than PHP 4, foreach will also be unavailable, so you will need to stick with list and each. Also to make in forward compatible, use third parameter for strict comparison:

if (!function_exists('in_array')) {
   function in_array($needle, $haystack, $strict = false) {
       while (list($key, $item) = each($haystack)) {
           if ($strict && $needle === $item) {
               return true;
           } else if (!$strict && $needle == $item) {
               return true;
           }
       }
       return false;
   }
}

Upvotes: 2

Manoj Yadav
Manoj Yadav

Reputation: 6612

Create your own in array function something like below:

function my_in_array($value, $arr) {
    foreach ($arr as $a) {
        if ($a == $value) {
            return true;
        }
    }
    return false;
}

Upvotes: 0

federicot
federicot

Reputation: 12341

Use a custom function. For future compatibility, you could use function_exists to check if the current version of PHP that you're using does indeed have in_array.

function inArray($needle, $haystack)
{
    if (function_exists('in_array')) {
        return in_array($needle, $haystack);
    } else {
        foreach ($haystack as $e) {
            if ($e === $needle) {
                return true;
            }
        }

        return false;
    }
}

Upvotes: 4

bizzehdee
bizzehdee

Reputation: 21023

You can create your own function to mimic the functionality with

function my_in_array($ar, $val)
{
  foreach($ar as $k => $v)
  {
    if($v == $val) return true;
  }
  return false;
}

or if you looking for a key

function my_in_array($ar, $val)
{
  foreach($ar as $k => $v)
  {
    if($k == $val) return true;
  }
  return false;
}

Upvotes: 0

Lee
Lee

Reputation: 10603

Without checking what functions were available in what versions, and comparing against the version you are using (we're not php.net encyclopedia's), your best bet is to go back to basics, and just loop through and check.

function in_array($val, $array) {

   foreach($array as $a) {

      if($a === $val)
          return true;

   }

   return false;

}

Upvotes: 0

Related Questions