Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

in_array

(PHP 4, PHP 5)

in_array -- Проверить, присутствует ли в массиве значение

Описание

bool in_array ( mixed needle, array haystack [, bool strict] )

Ищет в haystack значение needle и возвращает TRUE в случае удачи, FALSE в противном случае.

Если третий параметр strict установлен в TRUE тогда функция in_array() также проверит соответствие types параметра needle и соответствующего значения массива haystack.

Замечание: Если needle - строка, сравнение будет регистрозависмым.

Замечание: В PHP версий, более ранних, чем 4.2.0 параметр needle не может быть массивом.

Пример 1. Пример использования in_array()

<?php
$os
= array("Mac", "NT", "Irix", "Linux");
if (
in_array("Irix", $os)) {
    echo
"Got Irix";
}
if (
in_array("mac", $os)) {
    echo
"Got mac";
}
?>

Второго совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:

Got Irix

Пример 2. Пример использования in_array() с параметром strict

<?php
$a
= array('1.10', 12.4, 1.13);

if (
in_array('12.4', $a, true)) {
    echo
"'12.4' found with strict check
"
;
}

if (
in_array(1.13, $a, true)) {
    echo
"1.13 found with strict check
"
;
}
?>

Результат выполнения данного примера:

1.13 found with strict check

Пример 3. Пример использования in_array() с массивом в качестве параметра needle

<?php
$a
= array(array('p', 'h'), array('p', 'r'), 'o');

if (
in_array(array('p', 'h'), $a)) {
    echo
"'ph' найдено
"
;
}

if (
in_array(array('f', 'i'), $a)) {
    echo
"'fi' найдено
"
;
}

if (
in_array('o', $a)) {
    echo
"'o' найдено
"
;
}
?>

Результат выполнения данного примера:

'ph' найдено
  'o' найдено

См. также array_search(), array_key_exists() и isset().



key> <extract
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
in_array
f d0t fesser att gmx d0t net
16-Oct-2007 03:20
In case you have to check for unknown or dynamic variables in an array, you can use the following simple work-around to avoid misleading checks against empty and zero values (and only these "values"!):

<?php
  in_array
($value, $my_array, empty($value) && $value !== '0');
?>

The function empty() is the right choice as it turns to true for all 0, null and ''.
The '0' value (where empty() returns true as well) has to be excluded manually (as this is handled by in_array correctly!).

Examples:
<?php
  $val
= 0;
 
$res = in_array($val, array('2007'));
?>

leads incorrectly to true where

<?php
  $val
= 0;
 
$res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>

leads correctly to false (strict check!) while

<?php
  $val
= 2007;
 
$res = in_array($val, array('2007'), empty($val) && $val !== '0');
?>

still correctly finds the '2007' ($res === true) because it ignores strict checking for that value.
iair salem at -first g then mail.com-
24-Sep-2007 11:08
@Abro:
I saw strcasecmp() to be recommended rather than strtolower()
info at b1g dot de
02-Aug-2007 10:44
Be careful with checking for "zero" in arrays when you are not in strict mode.
in_array(0, array()) == true
in_array(0, array(), true) == false
Abro
07-Jun-2007 04:00
Well, ok - it's really not that fast when you test case-insensitive. but its ok.
i use it for spider/bot identification. as you can imagine there are a lot of useragents to check for in the database after some time.

-this is <vandor at ahimsa dot hu>'s function a lil bit extendet. (senseless? maybe...)

function is_in_array($needle, $haystack, $case_sensitive=true)
  {
    if($case_sensitive===false)
      $needle=strtolower($needle);
     
    foreach($haystack as $v)
    {
        if(!is_array($v))
        {
          if(!$case_sensitive)
            $v=strtolower($v);
         
          if($needle == $v)        
            return true;
        }
        else
        {
            if(is_in_array($needle, $v, $case_sensitive) === true)
              return true;
        }
    }
    return false;
  }
Abro
07-Jun-2007 02:40
RE: In trying to emulate a case insensitive in_array()....

why not :

foreach the parameter vals, strtolower them
and after that have a small and simple in_array functioncall ... ?

should be mouch smarter ;)
ashw1 - at - no spam - post - dot - cz
02-Jun-2007 01:54
If you ever need to print out an table of 2-dimensional array, here is one I made:

<?php
function MakeTableOf2DArray($db)
    {
   
$col_cnt=0; $row_cnt=0;
   
$col = array(); $row = array();

    foreach (
$db as $key => $val)
        {
        if (!
in_array($key,$col,true))
            {
           
$col[$col_cnt] = $key;
           
$col_cnt++;
            }
        foreach (
$val as $skey => $sval)
            {
            if (!
in_array($skey,$row,true))
                {
               
$row[$row_cnt] = $skey;
               
$row_cnt++;
                }
            }
        }

   
$res = '<table><tr><td width="100">'.$col[$i].'</td>';
    for (
$i=0;$i<$col_cnt;$i++)
        {
       
$res .= '<td width="100">'.$col[$i].'</td>';
        }
   
$res .= '</tr>'."\n";

    for (
$i=0;$i<$row_cnt;$i++)
        {
       
$res .= '<tr>';
       
$res .= '<td>'.$row[$i].'</td>';
        for (
$o=0;$o<$col_cnt;$o++)
            {
           
$res .= '<td>'. (isset($db[$col[$o]][$row[$i]])? $db[$col[$o]][$row[$i]]: '&nbsp;').'</td>';
            }
       
$res .= '</tr>'."\n";
        }

   
$res .= '</table>';
    return
$res;
    }

//example

$db = Array
(
   
'ab' => Array
        (
           
'janik' => 1 ,
           
'vendula' => 3 ,
           
'eva' => 5
       
) ,

   
'lg' => Array
        (
           
'janik' => 4 ,
           
'eva' => 2 ,
           
'misa' => 6
       
)

);

echo
MakeTableOf2DArray($db);

?>

prints out:

|         | ab | lg |
| janik   | 1  | 4  |
| vendula | 3  |    |
| eva     | 5  | 2  |
| misa    |    | 6  |
anonymous
22-May-2007 01:22
@mike at php-webdesign dot nl

will not work as desired if you don't check for strict in the recurssion
Quaquaversal
20-May-2007 08:48
A simple function to type less when wanting to check if any one of many values is in a single array.

<?php
function array_in_array($needle, $haystack) {
   
//Make sure $needle is an array for foreach
   
if(!is_array($needle)) $needle = array($needle);
   
//For each value in $needle, return TRUE if in $haystack
   
foreach($needle as $pin)
        if(
in_array($pin, $haystack)) return TRUE;
   
//Return FALSE if none of the values from $needle are found in $haystack
   
return FALSE;
}
?>
Bodo Graumann
16-Mar-2007 11:43
Be careful!

in_array(null, $some_array)
seems to differ between versions

with 5.1.2 it is false
but with 5.2.1 it's true!
ben
27-Feb-2007 01:25
Becareful :

$os = array ("Mac", "NT", "Irix", "Linux");
if ( in_array(0, $os ) )
   echo 1 ;
else
   echo 2 ;

This code will return 1 instead of 2 as you would waiting for.
So don't forget to add the TRUE parameter :

if ( in_array(0, $os ) )
   echo 1 ;
else
   echo 2 ;

Thie time it will return 2.
mike at php-webdesign dot nl
12-Feb-2007 01:11
@vandor at ahimsa dot hu

Why first check normal and then strict, make it more dynamically??

<?php
function in_arrayr($needle, $haystack, strict = false) {
    if(
$strict === false){
        foreach (
$haystack as $v) {
            if (
$needle == $v) return true;
            elseif (
is_array($v))
                if (
in_arrayr($needle, $v) == true) return true;
          }
        return
false;
    } else {
        foreach (
$haystack as $v) {
            if (
$needle === $v) return true;
            elseif (
is_array($v))
                if (
in_arrayr($needle, $v) === true) return true;
          }
        return
false;
    }
?>
vandor at ahimsa dot hu
05-Jan-2007 03:20
this "14-Jan-2006 06:44" example correctly:

in_arrayr -- Checks if the value is in an array recursively

Description
bool in_array (mixed needle, array haystack)

<?

function in_arrayr($needle, $haystack) {
  foreach ($haystack as $v) {
    if ($needle == $v) return true;
    elseif (is_array($v)) {
      if (in_arrayr($needle, $v) === true) return true;
    }
  }
  return false;
}

?>
RQuadling at GMail dot com
29-Nov-2006 05:08
In trying to emulate a case insensitive in_array(), I came up with ...

<?php
function in_array_caseless($m_Needle, array $a_Haystack, $b_Strict = False)
    {
   
// Let's assume the function will fail.
   
$b_Result = False;

   
// Compare array vs array
   
if (is_array($m_Needle))
        {
       
// Iterate the Haystack to compare each Bale with the Needle.
       
foreach($a_Haystack as $a_Bale)
            {
           
// Determine the intersection between the Needle and the Bale.
            // Strictness indicates that the associative indexes must also match using case insensitivity.
           
if (
                (
$b_Strict && (array_uintersect_uassoc($m_Needle, $a_Bale, 'strcasecmp', 'strcasecmp') === $m_Needle)) ||
                (!
$b_Strict && (array_uintersect($m_Needle, $a_Bale, 'strcasecmp') === $m_Needle))
                )
                {
               
// It it matches then we have a winner.
               
$b_Result = True;

               
// Don't process anything else as 1 match is all that is required.
               
break;
                }
            }
        }

   
// Compare everything else but reverse the Haystack and the Needle.
    // This is done as the return from array_uinterect is based upon its Needle
    // and we need the Haystack's type to compare for strictness.
   
else
        {
       
$a_Result = array_values(array_uintersect($a_Haystack, array($m_Needle), 'strcasecmp'));
       
$b_Result = !$b_Strict || (gettype($m_Needle) == gettype($a_Result[0]));
        }

   
// Return the result
   
return $b_Result;
    }
?>

For more info on this and other cool functions please see http://rquadling.php1h.com.
lafo
26-Nov-2006 08:36
The specification of this function is misleading.

<?php
$os
= array("mac"=>"Mac", "NT", "Irix", "Linux");
if (
in_array("mac", $os)) {
   echo
"Got mac";
}
// prints Got mac !!!
?>

in_array searches both values AND indexes IF it is not running in the strict mode!

Correct specification: Checks if a value or a key exists in an array. In the strict mode, checks if a value exists in an array.
mattsch at gmail dot com
26-Oct-2006 09:04
I'm not sure why you would do a loop for a function that needs to be fast.  There's an easier way:

function preg_array($strPattern, $arrInput){
        $arrReturn = preg_grep($strPattern, $arrInput);
        return (count($arrReturn)) ? true : false;
}
nongjianz at yahoo dot com
16-Sep-2006 06:08
in_array does not work for this case:

If all items of an array as elements (not as an array) are in another array. For example:

$arr1 = array("aaa", "bbb", "ccc", "ddd");
$arr2 = array("aaa", "bbb");

The following function is a solution to work it out:
<?
function arrElement_in_array($arr2, $arr1){
    foreach($arr2 as $v){
        if(in_array($v, $arr1)){
           $count++;
        }
    }
    //if all elements of arr2 are in arr1
    if($count==count($arr2)){
        return true;
    }
}
?>
emailfire at gmail dot com
17-Jul-2006 08:46
This function allows you to use regular expressions to search the array:

<?php
function preg_array($pattern, $array)
{
 
$match = 0;
    foreach (
$array as $key => $value)
        {
          if (
preg_match($pattern, $value))
              {
               
$match = 1;
                break;
        }
    }
 return (
$match == 1) ? true : false;
}
?>

An example:

<?php
$colors
= array('red', 'green', 'blue');

if (
preg_array("/green/i", $colors)) {
echo
"Match found!";
}
else {
echo
"Match not found!";
}
?>
musik at krapplack dot de
04-Jun-2006 05:52
I needed a version of in_array() that supports wildcards in the haystack. Here it is:

<?php
function my_inArray($needle, $haystack) {
   
# this function allows wildcards in the array to be searched
   
foreach ($haystack as $value) {
        if (
true === fnmatch($value, $needle)) {
            return
true;
        }
    }
    return
false;
}

$haystack = array('*krapplack.de');
$needle = 'www.krapplack.de';

echo
my_inArray($needle, $haystack); # outputs "true"
?>

Unfortunately, fnmatch() is not available on Windows or other non-POSIX compliant systems.

Cheers,
Thomas
rick at fawo dot nl
08-Apr-2006 08:23
Here's another deep_in_array function, but this one has a case-insensitive option :)
<?
function deep_in_array($value, $array, $case_insensitive = false){
    foreach($array as $item){
        if(is_array($item)) $ret = deep_in_array($value, $item, $case_insensitive);
        else $ret = ($case_insensitive) ? strtolower($item)==$value : $item==$value;
        if($ret)return $ret;
    }
    return false;
}
?>
Imre P
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571