Yaniv Golan
Yaniv Golan

Reputation: 982

adding an element to multidimensional array when within foreach loop (PHP)

I'm trying to check if a certain category is allready selected by looping through an array of categories also I want to add another element to the array whci is just a bit to indicate is the category selcated

my categories array looks like this

0=>array(category_id=>12,category_name=>"blogger")  
1=>array(category_id=>13,category_name=>"dancer")

etc...
now the code i'm trying goes like that:

foreach ($userCategories as $key=>$category) {
    if($category['category_id'] == $mediaDetails['currentCategory']) {
        $category['current'] = 1;
    } else {
        $category['current'] = 0;
    }
}

when executing

die(var_dump($userCategories));

I expect to get an array similar to

0=>array(category_id=>12,category_name=>"blogger",current=>0)  
1=>array(category_id=>13,category_name=>"dancer",current=>1)

but instead I get the same array I had before the foreach loop

any ideas?

Thanks

Upvotes: 2

Views: 5092

Answers (1)

zebediah49
zebediah49

Reputation: 7611

It looks like $category is not getting passed by reference.

Try $userCategories[$key]['current']=1 instead, and see how that works.

Upvotes: 11

Related Questions