-1

I have a list of people's names and ages. Through function array_filter(), I can filter people who are over 40 years old, which returns the correct answer But if I want to put a filter for the names of people, this issue does not work properly through the Strpos() function, for example, if I want to write the phrase sapi, the answer should include the names sapi and rahmatsapi, but the answer is not like that. I tried other functions such as the strpbrk() function, but they did not give the right answer.

$listL = [
['name' => 'sapi', 'age' => 49],
['name' => 'rahmatsapi', 'age' => 42],
['name' => 'neko', 'age' => 39]];

$filterUser = array_filter($listL, fn($user) => $user['age'] > 40);

$filterUser = array_filter($listL, fn($user) => strpos($user['name'], 'sapi'));

var_dump($filterUser);

If I definitely want to use array_filter()function and string functions, what is the correct way? If string functions do not have such capability, what is the alternative solution? Thanks

1
  • Check the big red box in the docs for strpos(). Commented Jun 8, 2023 at 20:42

1 Answer 1

0

here in my test it work. I believe that is cause strpos need be check with === rather then ==

$listL = [
['name' => 'sapi', 'age' => 49],
['name' => 'rahmatsapi', 'age' => 42],
['name' => 'neko', 'age' => 39]];

 $filterUserAge = array_filter($listL, function ($user){
    if($user['age'] > 40){
    return $user;
  }
});

$filterUserName = array_filter($listL, function($user){
$pos = strpos($user['name'], 'sapi');
$achou =false;

if($pos === false){
    return $achou;
}else{
   $achou = true;
    return $user;
 }
});

print_r($filterUserName);

Regards

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.