0

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
  • That's because your $keyword is empty! So check with empty() before you return if $keyword is empty! otherwise return like false or so! Commented Nov 21, 2014 at 5:00

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked - bringing $keyword into the scope did the trick.
You can use stripos - a case insensitive analogue of strpos. And since the stripos / strpos functions may return "non-Boolean value which evaluates to FALSE", I suggest you to return ( stripos($obj->title, $keyword) !== false );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.