如何获取特定的数组元素?

时间:2011-10-09 00:35:41

标签: php arrays

说我有以下字符串数组:

$data_array = array("the dog is hairy", "cats like treats", "my mouse is tired");

我想编写一个函数,根据它是否包含另一个字符串从数组中提取元素。

例如,如果数组元素包含字符串“dog”,我想返回字符串“狗是多毛的”,以便在其他地方使用。

我尝试使用foreach循环,但它不起作用:

foreach ($data_array as $sentence){
    if (stripos($sentence, "dog")){
        echo $sentence;
    }
}

最好的方法是什么?

5 个答案:

答案 0 :(得分:2)

对我来说很好。

http://sandbox.phpcode.eu/g/064bf

<?php 
$data_array = array("the dog is hairy", "cats like treats", "my mouse is tired"); 
foreach($data_array as $data){ 
    if (false !== stripos($data, "dog")){ 
        echo $data; 
    } 
}

答案 1 :(得分:2)

如果你想使用stripos,这就是代码:

   $data_array = array("the dog is hairy", "cats like treats", "my mouse is tired");
   foreach($data_array as $value)
   {
      if (stripos($value, 'dog') !== FALSE)
         echo $value;
   }

答案 2 :(得分:1)

foreach ($data_array as $val) {
  if (strstr($val, 'dog')) {
    echo $val;
  }
}

答案 3 :(得分:0)

您可以使用此示例:

$f_array = preg_grep('/dog/i', $data_array);  

答案 4 :(得分:-1)

您也可以使用preg_grep()

$found_array = preg_grep( '/dog/i', $data_array );

编辑:为不区分大小写的匹配添加了/i开关。