leoarce
leoarce

Reputation: 549

How do i explode multiple comma separated lists into a single foreach?

Let's say I have these 2 comma separated lists:

$quantity = "5000,10000";
$cost = "2.00,1.00";

Then I explode quantity to echo out each list item like this:

$quantity_explode = explode(",", $quantity);
foreach($quantity_explode as $quantity_value){
    echo $quantity_value . PHP_EOL; //PHP_EOL is same as \n
}

The result of that is:

5000
10000

But what I really want to display is this:

5000 2.00
10000 1.00

How do I incorporate the second list into the first list? The 1st value of 2nd list belongs to the 1st value of 1st list. The 2nd value of 2nd list belongs to the 2nd value of 1st list. And so on.

I don't think it's a second explode and second foreach after first explode and foreach (then do some kind of weird merge?). Do I do 2nd explode and foreach inside the first foreach?

Upvotes: 2

Views: 1330

Answers (5)

Keiran Tai
Keiran Tai

Reputation: 962

Yes, you can use another foreach() nested in the first loop. Or, if they're in sequence. Try to use on for() loop:

$qty = explode(',',  $quantity);
$c = explode(',',  $cost);
for($i=0; $i < count($qty); $i) {
  echo "$qty[$i] $c[$i]". PHP_EOF;
}

Upvotes: 0

Jia Jian Goi
Jia Jian Goi

Reputation: 1423

Do something like:

$quantity_explode = explode(",", $quantity);
$cost_explode = explode(",", $cost);
for ($i = 0; $i < count($quantity_explode); $i++) {
    echo $quantity_explode[$i] . " " . $cost_explode[$i] . PHP_EOL;
}

Assuming that you can be sure the number of delimited values in $quantity is of the same as $cost, and that the data of $quantity_explode[index] are associated with $cost_explode[index].

Upvotes: 1

Vojko
Vojko

Reputation: 804

How about

$quantity_explode = explode(",", $quantity);
$cost_explode = explode(",", $cost);
    for($i=0; $i<count($quantity_explode); $i++)
     {
echo $quantity_explode[$i]. ' ' . $cost_explode[$i] . PHP_EOL; //PHP_EOL is same as \n
}

Upvotes: 1

Mark Manning
Mark Manning

Reputation: 1467

Easy, make a third array and put each of the fields into that array as subfields. Then just do a foreach on the new array. Like so

$a = [];
for( $i=0; $i<count($quantity); $i++ ){
$a[$i]['quantity'] = $quantity[$i];
$a[$i]['cost'] = $cost[$i];
}
foreach( $a as $k=>$v ){
echo $v['quantity'] . " = " . $v['cost'] . "\n";
}

If this is a course item - you really should figure it out for yourself. :-)

Upvotes: 1

Gaurav Rai
Gaurav Rai

Reputation: 928

<?php
$quantity = "5000,10000";
$cost = "2.00,1.00";
$quantity_explode = explode(",", $quantity);
$cost_explode = explode(",", $cost);
for($i=0;$i<count($quantity_explode);$i++){
    echo $quantity_value[$i] . "-" . $cost_explode[$i] . PHP_EOL; //PHP_EOL is same as \n
}

Upvotes: 0

Related Questions