dev.e.loper
dev.e.loper

Reputation: 36064

How do I loop through array of values posted

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"
  }
}

Upvotes: 1

Views: 86

Answers (3)

TrippyD
TrippyD

Reputation: 735

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.

Upvotes: 0

Jaime
Jaime

Reputation: 1410

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

Notice the tick marks around ids in $_POST.

Upvotes: 0

Alex
Alex

Reputation: 2146

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

Don't forget about quotes..

Upvotes: 1

Related Questions