17

I like to perform a search on an array and return all values when a match is found. The key [name] in the array is what I am doing a search on.

Array (
[0] => Array
    (
        [id] => 20120100
        [link] => www.janedoe.com
        [name] => Jane Doe
    )
[1] => Array
    (
        [id] => 20120101
        [link] => www.johndoe.com
        [name] => John Doe
    )
)

If I did a search for John Doe it would return.

Array
(
    [id] => 20120101
    [link] => www.johndoe.com
    [name] => John Doe
)

Would it be easier to rename the arrays based on what I am searching for. Instead of the above array I can also generate the following.

Array (
[Jane Doe] => Array
    (
        [id] => 20120100
        [link] => www.janedoe.com
        [name] => Jane Doe
    )
[John Doe] => Array
    (
        [id] => 20120101
        [link] => www.johndoe.com
        [name] => John Doe
    )
)
Tim
  • 403
  • 1
  • 6
  • 20

3 Answers3

26
$filteredArray = 
array_filter($array, function($element) use($searchFor){
  return isset($element['name']) && $element['name'] == $searchFor;
});

Requires PHP 5.3.x

iBiryukov
  • 1,730
  • 4
  • 19
  • 30
  • 1
    As a function: `function so9439905_filter_array($array, $field, $search) { $filtered_array = array_filter($array, function($element) use($field, $search) { return isset($element[$field]) && $element[$field] == $search; }); return $filtered_array; };` Call via `so9439905_filter_array($array, 'name', 'John Doe');` – Leander Oct 04 '21 at 12:42
1

I would like to offer an optional change to scibuff's answer(which was excellent). If you are not looking for an exact match, but a string inside the array...

function array_search_x( $array, $name ){
    foreach( $array as $item ){
        if ( is_array( $item ) && isset( $item['name'] )){
            if (strpos($item['name'], $name) !== false) { // changed this line
                return $item;
            }
        }
    }
    return FALSE; // or whatever else you'd like
}

Call this with...

$pc_ct = array_search_x($your_array_name, 'your_string_here');
Tom aka Sparky
  • 76
  • 1
  • 11
1
$array = Array (
  [0] => Array(
    [id] => 20120100,
    [link] => www.janedoe.com,
    [name] => 'Jane Doe'
  ),
  [1] => Array(
    [id] => 20120101,
    [link] => www.johndoe.com,
    [name] => 'John Doe'
  )
);
$i = 0;
$new_array = [];
foreach($array as $key => $value){
  if($value['name'] === 'John Doe'){
    $key = $value['name'].$i;
    $new_array[] = [$key => $value];
    $i ++;
  }
}
return $new_array;
We Nobady
  • 11
  • 1
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Tyler2P Aug 22 '21 at 11:52