How to use strpos() in php when filtering an array

2.4k views Asked by At

I am trying to refine my array using strpos() , it`s works fine when i hardcode string manually but it fails if i pass the value using a variable.

Below code works fine.

  $filteredArray = array_filter($json_output, function($obj)
{ 
    return strpos(strtolower($obj->title), strtolower("Something"));
});

Below code does n`t work (Edit Posting full code for reference )

    <?php
$url = sprintf(
    '%s://%s/%s',
    isset($_SERVER['HTTPS']) ? 'https' : 'http',
    $_SERVER['HTTP_HOST'],
    $_SERVER['REQUEST_URI']
);    
    $parts = parse_url($url);
    parse_str($parts['query'], $query);

if (!empty($query['key'])) { 
$keyword = $query['key'];
$jsonurl = "url";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
$filteredArray = array_filter($json_output, function($obj)
{ 
    return strpos(strtolower($obj->title), strtolower($keyword));
});
echo json_encode($filteredArray);

}
else
{
    echo "Gods must be crazy";
}
?>

it throws following error - Warning: strpos() [function.strpos]: Empty needle.

Can someone please point out where i am doing it wrong?

1

There are 1 answers

2
khael On BEST ANSWER

You could try to use

$filteredArray = array_filter($json_output, function($obj) use ($keyword)
{ 
    return strpos(strtolower($obj->title), strtolower($keyword));
});

because it is in the scope of the function and you defined it at a higher level.

And also check with empty as was suggested in the comments.