phpcodeigniterparametersarray-walk

How to access others variable inside of array_walk?


I have a variable $id = 10, it's need to use inside of array_walk(). Like bellow :

$id = 10;
array_walk($profile_items, function(&$a) {
    $count = $this->db->where('profile_item_id', $a['id'])->where('cover_type_id', $id)->count_all_results('cover_type_profile_items_link');
    $a['selected'] = $id;
});
echo "<pre>";
print_r($profile_items).exit;

When i used $id variable inside of array_walk() it's show a error.

Message: Undefined variable: id

Any solution?

Thanks for Advice


Solution

  • You can use use keyword:

    array_walk($profile_items, function(&$a) use($id) {
    

    so,

    $id = 10;
    array_walk($profile_items, function(&$a) use($id) {
        $count = $this->db->where('profile_item_id', $a['id'])->where('cover_type_id', $id)->count_all_results('cover_type_profile_items_link');
        $a['selected'] = $id;
    });
    echo "<pre>";
    print_r($profile_items);
    

    To inherit by reference, add ampersand:

    array_walk($profile_items, function(&$a) use(&$id) {