S.M_Emamian S.M_Emamian - 1 year ago 54
PHP Question

search in values in array and get another value

I have an array like this:

//the result of `dd()` function in laravel

Collection {#401 ▼
#items: array:2 [▼
0 => {#400 ▼
+"tutorial_package_count": 2
+"tutorial_package_id": 1
+"tutorial_id": 1
}
1 => {#402 ▼
+"tutorial_package_count": 1
+"tutorial_package_id": 2
+"tutorial_id": 2
}
]
}


suppose I have a variable as
$tutorial_id = 1
,
now I want to get value of
tutorial_package_count
. at this here I want
2
.

I dont want to use a loop.

Answer Source

In this case you can use filter method available for collections:

$filtered = $collection->filter(function ($value, $key) use($tutorial_id) {
    return $value['tutorial_id'] == $tutorial_id;
});
$firstMatch = $filtered->first();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download