0

So I thought this would be easy, but try as I might various methods of appending values to an array in PHP, I always get NULL.

$sites = array();
$sites[0] = $_POST['site0'];
foreach($sites as $site) {
    var_dump($site);
}

$_POST['site0'] is an HTML form array, containing 11 keys and values. I get a invalid argument error for line 3. Any reason why this would occur?

6
  • I don't get null, but are you sire _POST[site0] is set? Commented Dec 11, 2011 at 16:52
  • The way to add values to an array is like $arr[] = 'new item'; specify more dimensions depending on structure as needed e.g. $arr[0][] = .... It makes no sense at all that var_dump would print null with the above code. Is that what you really have? Commented Dec 11, 2011 at 16:53
  • 1
    are you sure there is not typo? Or missing a BIG chunk of code before the var_dump? Commented Dec 11, 2011 at 16:54
  • what gives you var_dump($_POST['site0']) this code? Commented Dec 11, 2011 at 16:58
  • Okay, it seems that the real problem is not that the array $sites is NULL — I have fixed that, it was an error in the HTML — but rather that foreach($sites as $site) gives me "invalid argument". There are going to be more sites, and I'd like to cycle through and process them. Commented Dec 11, 2011 at 17:03

3 Answers 3

2

Probably, $_POST['site0'] is null or empty.

You could push the value to the $sites array doing so:

$sites[] = $_POST['site0'];

The value will be pushed to the end of the array.

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

Comments

1

It's really work. Just check your

$_POST['site0'];

and try add

$sites[1] = 'spam';

Comments

0

Your code works for me (see codepad):

Code

$_POST['site0'] = 'foobar';
$sites = array();
$sites[0] = $_POST['site0'];
var_dump($sites); // returns NULL

Result

array(1) {
  [0]=>
  string(6) "foobar"
}

Try to var_dump($_POST); to see what's actually contained in $_POST.

1 Comment

Turns out the problem is slightly different than what I thought it was — I've changed the question to reflect this.

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.