PHP foreach和strpos新手

时间:2014-06-08 21:00:53

标签: php strpos

为什么这不起作用?

$statement = array(
   images_name[0] => 'small_01.jpg', 
   images_name[1] => 'large_01.jpg', 
);

foreach ($statement->images as $image): 
if (strpos($image->name, 'small')) { 
    echo ('yes');
}
endforeach

我可以毫无问题地打印图像名称,但strpos无效。

2 个答案:

答案 0 :(得分:0)

strpos工作,但它返回0 - 您的单词在文件名中的位置 更好的解决方案:

strstr($image->name, 'small') !== false

Strstr函数将在找不到字符串时返回false或找到位置时返回。{/ p>

答案 1 :(得分:0)

您必须使用:

foreach ($statement->images as $image)
  if ( strpos($image->name, 'small') !== false ) { 
    echo ('yes');
  }

在这里解释: http://us3.php.net//manual/en/function.strpos.php

另外,如果您想知道为什么需要使用“!==”或“===”,请阅读以下内容: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?