0

Possible Duplicate:
foreach with three variables add

I'm new to PHP so bear with me.

I have a url with two variables like so:

 ?foo=1,2,3,4&bar=a,b,c,d

Both parameters will always have the same amount of elements. I need to loop through the amount of elements like so:

1a
2b
3c
4d

and on each iteration assign two variables for foo and bar value.

If this was javascript no problem, but I have no idea how to do this PHP. This is what I have:

$foo = strtok($rvar_foo,",");
$bar = strtok($rvar_bar,",");
while ( $foo ){
  # now how do I get the corresponding value for $bar?
}
Community
  • 1
  • 1
frequent
  • 27,643
  • 59
  • 181
  • 333
  • 1
    possible duplicate of [Multiple index variables in PHP foreach loop](http://stackoverflow.com/questions/4157810/multiple-index-variables-in-php-foreach-loop) ; [foreach with three variables add](http://stackoverflow.com/questions/7748115/foreach-with-three-variables-add) – hakre Oct 08 '12 at 21:03
  • 1
    there should also be tons of duplicates for the second part about how to use strtok or convert string to array by comma. – hakre Oct 08 '12 at 21:05
  • I'm trying strtok-ing right now. – frequent Oct 08 '12 at 21:18

3 Answers3

4
$foo = isset($_GET['foo']) ?  explode(",", $_GET['foo']) :  array();
$bar = isset($_GET['bar']) ?  explode(",", $_GET['bar']) :  array();

for ($i = 0; $i < count($foo); $i++) {
    echo $foo[$i] . $bar[$i] . "<br />";
}

Is this what you want?

Output

1a
2b
3c
4d
Baba
  • 94,024
  • 28
  • 166
  • 217
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
3

Use array_map:

function my_function($a, $b)
{

    var_dump($a . $b );
    // Do something with both values.
    // The first parameter comes from the first array, etc.
}

array_map("my_function", explode(",",$_GET['a']), explode(",",$_GET['b']));
Baba
  • 94,024
  • 28
  • 166
  • 217
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
1

Maybe you are looking for array_combine. It creates an array from two arrays, using one array for the keys, the other array for the values.

$foo = explode(',', $_GET['foo']);
$bar = explode(',', $_GET['bar']);
$foobar = array_combine($foo, $bar);

This would result in $foobar using the values from $foo as its keys and $bar for the values.

Calling print $foobar[1] would result in a being printed to the output. (You can find a running example here)

clentfort
  • 2,454
  • 17
  • 19