1

In my current project, I need to add a loop contents to an array where I can use it later. This is my code. I tried some way but they're not working. Can anybody give a help to fix it:

for($i=0;$i<$max;$i++) {
    $pid = $_SESSION['cart'][$i]['productid'];
    $q = $_SESSION['cart'][$i]['qty'];
    $pname = get_product_name($pid);

    if($q == 0) { 
        continue;
    } else {
        $j = $i+1;
    }

I need to add the $pid to an array where I should be able to use implode(",", $pid)

Thanks

5 Answers 5

2

Do you just mean this?

$pids = array();
for($i=0;$i<$max;$i++)
{
    $pid=$_SESSION['cart'][$i]['productid'];
    $q=$_SESSION['cart'][$i]['qty'];
    if($q==0)
    { 
        continue;
    }
    // optimization... don't do anything if quantity is 0.
    $pids[] = $pid;
    $pname=get_product_name($pid);
}
echo implode(',', $pids);
Sign up to request clarification or add additional context in comments.

Comments

1
$pids=array();
for($i=0;$i<$max;$i++){
  $pid=$_SESSION['cart'][$i]['productid'];
  $pids[]=$pid;
  $q=$_SESSION['cart'][$i]['qty'];
  $pname=get_product_name($pid);
  if($q==0){ 
    continue;
  }else{
    $j = $i+1;
  }
}
echo implode(' - ',$pids);

You should be a little more clear about what your end result should be, I could be a bit more specific

1 Comment

Thanks a lot mate, your method is working, that's what I really looking for :)
0

initialiaze $pid as an array first

$pid = array();

Now in your loop add the values to it

$pid[] =$_SESSION['cart'][$i]['productid'];

note the square brackets with pid

after your loop you can extract the values from $pid

$someValue = $pid[0] * something';

I hope this is what u are looking for

2 Comments

actually I need an output like $id = 10,12,13 I tried yours mate, but its not what I wanted
you simply have to implode the $pid variable, i gave you a generic answer so you can understand the concept
0
$pids = array();

foreach ($_SESSION['cart'] as $cart)
{
 $pids[] = $cart['productid'];
}

This will get you a $pids array.

Comments

0

I would suggest you initialize an array for your pids

$arr_pids = array()

and each time you want to add a pid to this array just use

array_push($arr_pids, $pid)

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.