How to use array_filter with callback in php 5.2 [duplicate]

流过昼夜 提交于 2019-12-31 05:31:08

问题


I am trying to use array_filter with call back in php 5.2, but I get the following error:

Parse error: syntax error, unexpected T_FUNCTION

And I did search the solution using the error in Google search and found that Php 5.2 does not support callback. The code I am working on is:

$result = array_filter($lines, function($line) {
  return stripos($line,"ID:")!==false;
});

How do I change it so that It can work in php 5.2? Any help and workaround would be very much appreciated. Thanks.


回答1:


Anonymous functions was introduced in PHP 5.3, so if you are using PHP 5.2 or lower you need to define the function explicitly and pass the functions name as the second argument of array_filter(), as shown below.

$result = array_filter($lines, 'filter');

function filter($line) {
    return stripos($line,"ID:") !== false;
}

Consider upgrading to a newer version of PHP if you can.

  • PHP.net on array_filter()
  • PHP.net on anonymous functions
  • PHP.net on the Closure class


来源:https://stackoverflow.com/questions/37985222/how-to-use-array-filter-with-callback-in-php-5-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!