0

I did have a quick search on this but couldn't find anything relating to my problem. I'm having issues with an if statement within a foreach loop. I'm pulling a list of categories from one class, and a single category to be selected from another. The code below (with the if statement removed) works perfectly, and returns 12 options with populated values.

foreach ($user_info->categories as $key=>$category) {
    $category_name = $user_info->category_names[$key];
    echo '<option value="'.$category.'">'.$category_name.'</option>';
}

However when I add the if statement inside as below:

foreach ($user_info->categories as $key=>$category) {
    $category_name = $user_info->category_names[$key];
    if ($category = $get_article_info->category_1) {
        echo '<option value="'.$category.'" selected="selected">'.$category_name.'</option>';
    } else {
        echo '<option value="'.$category.'">'.$category_name.'</option>';
    }
}

I get a list of options with the text populated but all twelve options have value="". $get_article_info->category_1 works when echoed on it's own, and even if it were not found I would expect the if statement to echo 12 options without any selected (the same as the first code example).

1 Answer 1

4

You are using = instead of == You should change

 if ($category = $get_article_info->category_1) {

To

  if ($category == $get_article_info->category_1) {
Sign up to request clarification or add additional context in comments.

1 Comment

Spot on! Cheers for that, minor oversight.

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.