1

I am having trouble dynamically naming my PHP variables when doing a foreach loop. Here is my code:

$count = count($_POST['member']);
for ($i = 0; $i < $count; $i++) {
    $fname = $_POST['member'][$i]['fname'];
    $lname = $_POST['member'][$i]['lname'];
}

How would I append the number contained in $i to $fname & $lname so that $fname & $lname become $fname1 & $lname_2 and so on? Or is there a better way of doing this? Nothing I have tried works.

three3
  • 2,756
  • 14
  • 57
  • 85
  • What's your ultimate goal with this? – Steven Moseley Dec 04 '12 at 05:04
  • @TheSmose My main goal is to store all of the information in $_SESSION variables that can be retrieved later. Say there are 7 new "Contacts" added, I want to loop through the data and store each value to $_SESSION variables – three3 Dec 04 '12 at 05:07

4 Answers4

1
$i = 0;
$output = array();

foreach ($_POST['member'] as $member)
{
   $output['fname' . $i] = $member['fname'];   
   $output['lname' . $i] = $member['lname'];
   $i++;
}

extract($output);

Though..why?

wesside
  • 5,622
  • 5
  • 30
  • 35
  • snap... +1 for posting ahead of me using `extract` – Muthu Kumaran Dec 04 '12 at 05:12
  • @bigman My main goal is to store all of the information in $_SESSION variables that can be retrieved later. Say there are 7 new "Contacts" added, I want to loop through the data and store each value to $_SESSION variables – three3 Dec 04 '12 at 05:12
  • So change $output to $_SESSION..This is baddd practice man. At very least store $output into the session and exact that later..but hell, I would just find a better way to go about this. – wesside Dec 04 '12 at 05:14
0

EDIT: Answer to your new question - how to store in the session:

session_start();
$count = count($_POST['member']);
for ($i = 0; $i < $count; $i++) {
    $_SESSION["fname_{$i}"] = $_POST['member'][$i]['fname'];
    $_SESSION["lname_{$i}"] = $_POST['member'][$i]['lname'];
}
Steven Moseley
  • 15,871
  • 4
  • 39
  • 50
0

Try this

$count = count($_POST['member']);
for ($i = 0; $i < $count; $i++) {
 $fname.'_'.$i = $_POST['member'][$i]['fname'];
 $lname.'_'.$i = $_POST['member'][$i]['lname'];
}

So you can access $fname_1,$fname_2 etc...

Sanjay
  • 761
  • 14
  • 25
-1

Hi try the simple concatination(".") operator of php.. So your code will be

$count = count($_POST['member']);
for ($i = 0; $i < $count; $i++) {
    $fname = $_POST['member']['fname'.$i];
    $lname = $_POST['member']['lname_'.$i];
}
Ayyappan Sekar
  • 11,007
  • 2
  • 18
  • 22