0

I have encountered a problem when trying to add values to an array through a foreach loop. Basically I have this form where there's a bunch of topics that the user can click 'like' or 'dislike' on with two radio-buttons per topic. I then want to collect the "likes" and the "dislikes" in two separate arrays, and insert them into a database, but something I don't do correct. Here is a sample from the HTML code:

Action movies  Like<input type="radio" name="1" value="1" />  Dislike<input type="radio" id="2" name="1" value="2" />

And the PHP code:

if (isset($_POST['submit'])) {
    $likes = array();
    $dislikes = array();

    foreach($_POST as $key => $value) {

        /* $key is the name of the object an user can click "like" or "dislike" on, $value   
        is either 'like', which is equal to '2' or 'dislike', equal to '1' */
        if ($value > 1) { array_push($likes, $key); } else { array_push($dislikes, $key); 
    }
} 
echo 'The object(s) the user likes: ' . $likes . ' , 
       and the object(s) the user dislikes: ' . $dislikes;

I however receive this:

"The object(s) the user likes: Array , and the object(s) the user dislikes: Array"

1
  • Id & name can't be only numbers (or starting with one) Commented Jul 25, 2012 at 12:46

1 Answer 1

2

An array when cast to a string will simply be output as the string "Array". If you want to output each element in the array, loop through them or use something like join:

echo join(', ', $likes);

array_push is working just fine.

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

4 Comments

+1, But curious why you used the alias join() vs. implode() directly?
Cause it makes more sense to me and doesn't have any downsides.
@Danny BTW, $likes[] = $key; is the usual idiom instead of array_push.
@deceze, is there some reason for $likes[] = $key; being more usual than array_push?

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.