skip to Main Content

I’m wondering if you guys can give me an idea about how to replace this each function:

while(list($key,$val) = each($_SESSION['cart'][$i]))
        {
            if ($key=="product_name"){
                $product_name=$val;
            }else if($key=="units"){
                $units=$val;
            }else if($key=="packing_size"){
                $packing_size=$val;
            }else if($key=="grade"){
                $grade=$val;
            }else if($key=="length"){
                $length=$val;
            }else if($key=="quantity"){
                $quantity=$val;
            }
        }
        echo $product_name."".$units."".$packing_size."".$grade."".$length."".$quantity;
        echo "<br>";
    }

Thanks!

I’ve try to use foreach, but isn’t working at all

2

Answers


  1. I assume your original question is "How to replace a deprecated loop with each()"…?
    In this case ADyson’s commentary will be of great help to you.

    But then why carry out tests on keys to obtain values ​​that you then place in variables that you only display…?
    If you just want to display the values ​​you can access your array through the keys
    As in the code below

    foreach($_SESSION['cart'][$i] as $key => $val)
    {
        echo $val["product_name"]."".$val["units"]."".$val["packing_size"]."".$val["grade"]."".$val["length"]."".$val["quantity"];
        echo "<br>";    
    }
    
    Login or Signup to reply.
  2. for a more elegant solution and better optimisation you can use foreach and a switch statement

    foreach ($_SESSION['cart'][$i] as $key => $val) {
        switch ($key) {
            case "product_name":
                $product_name = $val;
                break;
            case "units":
                $units = $val;
                break;
            case "packing_size":
                $packing_size = $val;
                break;
            case "grade":
                $grade = $val;
                break;
            case "length":
                $length = $val;
                break;
            case "quantity":
                $quantity = $val;
                break;
        }
    }
    echo $product_name . "" . $units . "" . $packing_size . "" . $grade . "" . $length . "" . $quantity;
    echo "<be>";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search