检查数组中是否存在某个值 php-数组函数in_array()

来源:互联网 发布:linux shell 脚本 编辑:程序博客网 时间:2024/05/17 00:06
bool in_array ( mixed $needle, array $haystack [, bool $strict] )

在 haystack 中搜索 needle,如果找到则返回 TRUE,否则返回 FALSE。 

如果第三个参数 strict 的值为 TRUE 则 in_array() 函数还会检查 needle 的类型是否和 haystack 中的相同。 

注意: 如果 needle 是字符串,则比较是区分大小写的。 

注意: 在 PHP 版本 4.2.0 之前,needle 不允许是一个数组。 

例  in_array()

  1. <?php
  2. $os = array("Mac""NT""Irix""Linux");
  3. if (in_array("Irix"$os)) {
  4.     echo "Got Irix";
  5. }
  6. if (in_array("mac"$os)) {
  7.     echo "Got mac";
  8. }
  9. ?> 
输出: Got Irix

严格类型检查


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

  3. if (in_array('12.4'$a, true)) {
  4.     echo "'12.4' found with strict check/n";
  5. }
  6. if (in_array(1.13, $a, true)) {
  7.     echo "1.13 found with strict check/n";
  8. }
  9. ?>  
输出:1.13 found with strict check 

用数组作为 needle
  1. <?php
  2. $a = array(array('p''h'), array('p''r'), 'o');

  3. if (in_array(array('p''h'), $a)) {
  4.     echo "'ph' was found/n";
  5. }
  6. if (in_array(array('f''i'), $a)) {
  7.     echo "'fi' was found/n";
  8. }
  9. if (in_array('o', $a)) {
  10.     echo "'o' was found/n";
  11. }
  12. ?>  
输出:'ph' was found
      'o' was found
0 0
原创粉丝点击