1

I'm posting an array of ids and want to loop over those values. I'm trying the following to populate an array with key/value pairs but it looks like the array is coming out empty.

$arr = array();
foreach($_POST['ids'] as $id)
{
   $arr[$id] = GetStuff($id);
}

UPDATE: Looks like array was populated fine. I'm trying to return contents of array by doing echo json_encode($arr) but response is blank.

Here is output of var_dump($_POST);

  array(1) {
  ["ids"]=>
  array(18) {
    [0]=>
    string(6) "156795"
    [1]=>
    string(6) "156800"
    [2]=>
    string(4) "4292"
    [3]=>
    string(6) "796053"
    [4]=>
    string(6) "660520"
    [5]=>
    string(4) "4293"
    [6]=>
    string(4) "4287"
    [7]=>
    string(6) "488339"
    [8]=>
    string(6) "837701"
    [9]=>
    string(7) "1152093"
    [10]=>
    string(7) "1186434"
    [11]=>
    string(7) "1324432"
    [12]=>
    string(6) "796051"
    [13]=>
    string(6) "144860"
    [14]=>
    string(5) "15065"
    [15]=>
    string(7) "1324434"
    [16]=>
    string(5) "13066"
    [17]=>
    string(4) "6969"
  }
}
11
  • Define "doesn't work". The code is O.K. for this purpose, how do you send the array? Can you give us a var_dump($_POST);? Commented Sep 28, 2011 at 21:01
  • Do you have $_POST[ids] or $_POST['ids'] in your code? Commented Sep 28, 2011 at 21:03
  • sorry. updated my question with more details Commented Sep 28, 2011 at 21:04
  • Scoutman, I see you point, but this doesn't explain the error as PHP will fallback to the string 'ids' (still, it should be 'ids' in the code). Commented Sep 28, 2011 at 21:05
  • 1
    @dev.e.loper: In that case your code will perfectly work. Please post GetStuff(), the error must be in there. Commented Sep 28, 2011 at 21:26

3 Answers 3

1
foreach($_POST['ids'] AS $i=>$id) {
    //do stuff
}

Don't forget about quotes..

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

1 Comment

my apologies, i didn't copy code verbatim. i do have single quotes around ids in $_POST['ids']. so that is not the issue.
0
$arr = array();
foreach($_POST['ids'] as $id)
{
   $arr[$id] = GetStuff($id);
}

Notice the tick marks around ids in $_POST.

1 Comment

my apologies, i didn't copy code verbatim. i do have single quotes around ids in $_POST['ids']. so that is not the issue.
0

This should work:

foreach($_POST['ids'] as $id)
{
   $arr[$id] = $_POST['ids'][$id];
}

or even faster, if you are just wanting an array identical to the posted ids:

$arr = $_POST['ids'];

unless I am misunderstanding the question.

Comments

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.