简体   繁体   中英

PHP: Foreach echo not showing correctly

The output should look like this:

1. Yougurt 4 units price 2000 CRC

But I'm currently getting this:

item. Y Y unitsYquantity. 3 3 units3code. S S unitsSprice. units

This is the script:

    <?php

session_start();

//Getting the list
$list[]= $_SESSION['list'];


//stock
$products = array(

      'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150, 
      'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
      'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
      'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
  );

//Saving the stuff
$_SESSION['list'] = array(
    'item' => ($_POST['product']), 
    'quantity' => ($_POST['quantity']),
    'code' => ($_POST['code']),
);

//price
$price = $products[($_SESSION['list']['item'])] * $_SESSION['list']['quantity'];

$_SESSION['list']['price'] = $price;


//listing
echo  "<b>SHOPPIGN LIST</b></br>";

foreach($_SESSION['list'] as $key => $item) 
{
    echo $key, '. ', $item['item'], ' ', $item['quantity'], ' units', $item['price'];
}

//Recycling list
$_SESSION['list'] = $list;

echo "</br> <a href='index.html'>Return to index</a> </br>";


//Printing session
print_r($_SESSION);

?>

The problem is that you are nested 1 level deeper in the arrays than you think you are. To make it clear, the $_SESSION may look lik this (just before entering the foreach):

array(1) { 
     ["list"] => array(3) {
           ["item"] => string(8) "Pineaple"
           ["quantity"] => int(30)
           ["price"] => int(15000)
     } 
} 

(you can use var_dump($var) or print_r($var) methods to see the value: http://php.net/manual/en/function.var-dump.php http://php.net/manual/en/function.print-r.php)

When iterating over $_SESSION["list"], you pass the loop 3 times. In the first iteration, $key is "item", $value "Pineaple".

echo $key, '. ', $item['item'], ' ', $item['quantity'], ' units', $item['price'];
    "item   .    P                   P                    units   <empty>"

Why? String "item" is obvious, it's just printed out.

$item['item'] -> 'item' is cast to (int)0, so the first character of $item (Pineaple) is printed: P (The examples of string->int conversion rules are for example here: http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion )

$item['quantity'] -> the same as above

$item['price'] -> since the price is much higher than the length of the string, empty string is printed: $myvar = "hi"; echo $myvar[12234]; // prints empty string $myvar = "hi"; echo $myvar[12234]; // prints empty string

In every iteration you get this output, just the first word is changing. Put echo "<br />" at the end of the iteration and you will see it.

I hope this helps you a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM