4

I have a large PHP array, similar to:

$list = array(
    array(
        'id'     = '3243'
        'link'   = 'fruits'
        'lev'    = '1'
    ),
    array(
        'id'     = '6546'
        'link'   = 'apple'
        'lev'    = '2'
    ),
    array(
        'id'     = '9348'
        'link'   = 'orange'
        'lev'    = '2'
    )
)

I want to get the sub-array which contains a particular id.

Currently I use the following code:

$id = '3243'
foreach ($list as $link) {
    if (in_array($id, $link)) {
        $result = $link;
    }
}

It works but I hope there is a better way of doing this.

3
  • 2
    Not really, no - although it seems like in_array would be better replaced with $link['id'] == $id
    – DaveRandom
    Dec 18, 2012 at 12:54
  • 1
    stackoverflow.com/questions/1019076/…
    – ke20
    Dec 18, 2012 at 12:54
  • @ke20 the answers there are mostly for multidimensional arrays, the solutions here are simpler somewhat (since OP's array is only bidimensional).
    – Armfoot
    Aug 27, 2018 at 20:49

3 Answers 3

4

You can

  • write $link['id']==$id instead of in_array($id, $link) whitch will be less expensive.
  • add a break; instruction after $result = $link; to avoid useless loops
1
  • This page could be use to close future duplicates but sadly the accepted answer isn't very clean / readable. Perhaps improve this answer with a complete code block and keep the explanation. Jan 13, 2018 at 5:36
2

While this answer wouldn't have worked when the question was asked, there's quite an easy way to solve this dilemma now.

You can do the following in PHP 5.5:

$newList = array_combine(array_column($list,'id'),$list);

And the following will then be true:

$newList[3243] = array(
                         'id'   = '3243';
                         'link' = 'fruits'; etc...
1
  • 3
    No, no, no, wait. Don't do this. Rather, go to array_column() in the php manual and read about its 3rd parameter. array_combine() should not be called. Jan 13, 2018 at 5:31
2

The simplest way in PHP 5.4 and above is a combination of array_filter and the use language construct in its callback function:

function subarray_element($arr, $id_key, $id_val = NULL) {
  return current(array_filter(
    $arr,
    function ($subarr) use($id_key, $id_val) {
      if(array_key_exists($id_key, $subarr))
        return $subarr[$id_key] == $id_val;
    }
  ));
}
var_export(subarray_element($list, 'id', '3243')); // returns:
// array (
//   'id' => '9348',
//   'link' => 'orange',
//   'lev' => '2',
// )

current just returns the first element of the filtered array. A few more online 3v4l examples of getting different sub-arrays from OP's $list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.