c4isgonnablow
c4isgonnablow

Reputation: 61

Why can't I loop through an array?

I get these numbers seperated by commas from a textarea but I get an error when I try to loop through them. How do I do it? This is my code:

$numbers = $_GET['numbers'];

foreach($numbers as $number){
echo $number;
}

Upvotes: 0

Views: 89

Answers (2)

Jonan
Jonan

Reputation: 2536

You should first make an array out of $numbers. You can do this by adding this line:

$numbers = explode(',', $_GET['numbers']);

Then, before you use them in the foreach loop you should use trim() to remove whitespace from the start and end:

foreach($numbers as $number){
    $number = trim($number);

    echo $number
}

Upvotes: 6

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

If $_GET['numbers'] is a comma-separated list, it's not an array.

foreach(explode(",",$_GET['numbers']) as $number)

Upvotes: 3

Related Questions