2012-08-18 22:58
浏览 61

PHP array_search()没有返回正确的索引

I am trying to find a certain line in a file. The file is I'm using the php function search_array(), but it is not giving me the proper key. This code just returns the first line of the file:

$newurl = file_get_contents("");
$array = explode("
$key = array_search('triggers_mc.pin_mc.triggerFunction = function () {', $array);
echo $array[$key];

Does anyone know why this is happening, or a fix for this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douyo770657
    douyo770657 2012-08-18 23:05

    It's happening because you are missing the 4 space characters from the beginning of your search term.

    $key = array_search('    triggers_mc.pin_mc.triggerFunction = function () {', $array);

    works fine.

    A possible solution if you don't want to include the spaces in your search term would be to loop through $array and trim the values before calling array_search.

    点赞 评论
  • doushun1870
    doushun1870 2012-08-18 23:05

    Array_search() returns the key for needle if it is found in the array, FALSE otherwise.

    (int)FALSE == 0

    Something is wrong with your $needle, array_search returns false, thus $key = 0;

    点赞 评论
  • dougu7546
    dougu7546 2012-08-18 23:06

    Add four spaces before your search value.

    点赞 评论