php array search partial match Hello
Have array
Array
(
[0] => Array
(
)
[1] => Array
(
[0] => 1
[1] =>
[2] => 42U703T6319
[3] => 23GRT3273240
)
[2] => Array
(
[0] => 2
[1] =>
[2] => 44AAD602383
[3] => 21873TT9996
)
[3] => Array
(
[0] => 3
[1] =>
[2] => 223MSK34345
[3] => 21428739996
)
)
Using this code search exact match
$positionInStr = array_search(223MSK34345, Arr::dot($myArray));
$arrayKeys = Str::of($positionInStr)->explode('.');
$k = $arrayKeys[0];
$myArray = $myArray[$k];
how search partial match
@www888 What do you mean partial search?
Any particular example?
@tisuchi
For ex. in some case array have such entry
[2] => 'text text 223MSK34345'
so if I need sarch 223MSK34345 array_search can not find
This code ' 223MSK34345 ' always end of sting . I need search partial match or last part string
@www888 should it return all matches or just the first?
@www888 ok something like (untested but I think it should work)
$item = collect($arr)->first(function($items) use ($search) {
foreach ($items as $item) {
if (Str::contains($item, $search)) {
return true;
}
}
return false;
});
@Sinnbeck
$arr attach array , $search ="223MSK34345"
getting error : explode(): Argument #2 ($string) must be of type string, Closure given
@www888 what line is giving the error?
@Sinnbeck
project\vendor\laravel\framework\src\Illuminate\Collections\Traits\EnumeratesValues.php: 321
public function firstWhere($key, $operator = null, $value = null)
{
return $this->first($this->operatorForWhere(...func_get_args())); //321 line
}
@www888 should have been first() not firstWhere(). Fixed my code
@Sinnbeck
Now it works but need return position (for my ex. 223MSK34345 position is 3)
@www888 then add a search() on the returned result find the index
@Sinnbeck
Cant understand : (
can you give example please
@www888 do you mean you need the index of the outer array?
$index = collect($arr)->search(function($items) use ($search) {
foreach ($items as $item) {
if (Str::contains($item, $search)) {
return true;
}
}
return false;
});
@Sinnbeck
Yes
my goal is find array where 223MSK34345
and then access value to display each in array 3
[3] => Array
(
[0] => 3
[1] => 123
[2] => 223MSK34345
[3] => 21428739996
)
@www888 not sure why you can't use my original example? Did you try it?
$item = collect($arr)->first(function($items) use ($search) {
foreach ($items as $item) {
if (Str::contains($item, $search)) {
return true;
}
}
return false;
});
dd($item); //gives you all results in index 3
I think there is a function dedicated for just this purpose, preg_grep. It should take a regular expression as first parameter, and an array as the second.
Please sign in or create an account to participate in this conversation.