2

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

1 Answer 1

11

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

Or fix the foreach foreach ($userCategories as $key=>&$category) { (note the &)
Right; I thought of that but wasn't positive that it would work properly in a foreach.
I thought that using the ampersand was deprecated? but I did a little test, but I didn't get any warnings php.net/manual/en/language.references.pass.php
I think & is only deprecated when you try to pass an argument as a reference when the function originally does not pass the argument as a reference.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.