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
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