Search code examples
phparraysforeachkeyvaluepairsub-array

Get the sub array in a bidimensional array having a particular key/value pair


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.


Solution

  • 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