1

Array:

$userdb = array(
    array(
        'uid' => '100',
        'name' => 'Sandra Shush',
        'pic_square' => 'abc.jpg'
    ),
    array(
        'uid' => '5465',
        'name' => 'Stefanie Mcmohn',
        'pic_square' => 'Michael.jpg'
    ),
    array(
        'uid' => '40489',
        'name' => 'Michael',
        'pic_square' => 'xyz.jpg'
    )
);

Search value:

Michael

Expected output:

$userdb = array(
    array(
        'uid' => '5465',
        'name' => 'Stefanie Mcmohn',
        'pic_square' => 'Michael.jpg'
    ),
    array(
        'uid' => '40489',
        'name' => 'Michael',
        'pic_square' => 'xyz.jpg'
    )
);

As you can check what I want can anyone please tell me How can I achieve this result by using PHP. I don't care whether my search term is in 'uid', 'name', or 'pic_square' key but I want to get array whenever my search term result is matching. Is there any inbuilt function which can achieve this result?

7
  • Can you please show the coding effort what you tried so far? Commented May 2, 2018 at 5:42
  • This, to me seems like a foreach nested inside another foreach... Commented May 2, 2018 at 5:43
  • @AlivetoDie my mind is blank I tried nothing. Please help me. Commented May 2, 2018 at 5:46
  • @RomeoSierra Any alternative way because element is too much. Commented May 2, 2018 at 5:47
  • @shahrushabh That's not how things work around here. Commented May 2, 2018 at 5:48

4 Answers 4

4

Another way is to use array_filter() to remove elements that not match to your search.

$userdb = array(
    array('uid' => '100', 'name' => 'Sandra Shush', 'pic_square' => 'abc.jpg'),
    array('uid' => '5465', 'name' => 'Stefanie Mcmohn', 'pic_square' => 'Michael.jpg'),
    array('uid' => '40489', 'name' => 'Michael', 'pic_square' => 'xyz.jpg')
);

$search = 'Michael';
$out = array_filter($userdb, function($item) use($search) {
    return $item['name'] == $search || strpos($item['pic_square'], $search) !== false;
});
print_r($out);

Output:

Array (
    [1] => Array (
            [uid] => 5465
            [name] => Stefanie Mcmohn
            [pic_square] => Michael.jpg
        )
    [2] => Array (
            [uid] => 40489
            [name] => Michael
            [pic_square] => xyz.jpg
        )
)
Sign up to request clarification or add additional context in comments.

2 Comments

$item['name'] == $search need to use strpos() too otherwise it will not work for a name like Michael Dominic..... I have this assumption only. Mind that I didn't say you are wrong.
You're right Alive. I use a full match here to show multiple possibilities. But I think a strpos for the name is probably more useful. Thank for your comment.
2

Very simple solution is to apply simple foreach() with strpos()

1.iterate over the array using foreach()

2.Check that search value exist in any one of three id, name,pic_square or not? if yes then add that whole sub-array to a new array.

3.This new array is your desired result.

$search_value = 'Michael';


$final_array = [];

foreach($userdb as $userd){
  if(strpos($userd['uid'],$search_value)!== false || strpos($userd['name'],$search_value)!== false || strpos($userd['pic_square'],$search_value)!== false){

     $final_array[] = $userd;
  }

}

print_r($final_array);

Output:- https://eval.in/997896

3 Comments

Bro thanks for a solution but I used array_search method it is fast. Same step I followed.
@shahrushabh glad to help you :):)
hi @AnantKumarSingh $market = [ 44434 => [ 34945, 44434, 41133, 41132, 49902 ], 49968=> [ 49968, 49967 ] ]; i want to do like this? if i give inner array value then get the above matched key i.e if we search 49902 then get 44434 this value
1

You can use preg_grep to match the search in a loose comparison.

$search = "Michael";
Foreach($userdb as $key => $arr){
    If(preg_grep("/" . $search ."/", $arr)){
        $res[] = $userdb[$key];
    }
}

Var_dump($res);

I loop through the array and if a match is made with preg_grep it's added to the result array.

https://3v4l.org/BPJBC

Preg_grep will search the full array and not only items hardcoded.
This can be both a good and a bad thing obviously.

As an example if your DB expands with 'alias' key preg_grep will search that to without needing to change the code.

See here for an example:
https://3v4l.org/lOao3

Comments

0

This should do the trick.

foreach($userdb as $i=>$r){
    foreach($r as $j=>$v){
        #if($v matches the querystring)
            #return $r / append $r to a match list
    }
}

But NOTE THAT since there are no indexing and all, this will run in O(N^2) which is the worst case...

EDIT

After some research, came up with the following solution.

$userdb = array(
    array(
        'uid' => '100',
        'name' => 'Sandra Shush',
        'pic_square' => 'abc.jpg'
    ),
    array(
        'uid' => '5465',
        'name' => 'Stefanie Mcmohn',
        'pic_square' => 'Michael.jpg'
    ),
    array(
        'uid' => '40489',
        'name' => 'Michael',
        'pic_square' => 'xyz.jpg'
    )
);

$search = "Michael";

$out = array_filter($userdb, function($item) use($search) {
    foreach($item as $k=>$v){
        if(preg_match("/$search/", $v) == 1){
            return true;
        }
    }
});

echo json_encode($out);

The solution employs array_filter function (Syscall's answer is acknowledged hereby, that was the pointer for me to research on array_filter further) to reduce the array using a filter, where the filter being a preg_match executed on each attribute of the associative array elements. If a match found, it returns true, which will add the matching element into $out.

3 Comments

2 foreach() is not required at all.
That's only if you know exactly how many items are there you already know all the keys to search for.. Did you downvote this??
I just asked out of curiosity.. :) Anyway, for all the approaches above, you need the complete knowledge of the keys upfront. If we don't know the keys, or if the keys in the associative arrays vary from one to another, you might be in trouble...

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.