Skip to content
Advertisement

PHP – Array For Loop Not Storing Values

I created an empty array and want to store values from another array coming from a form. I am getting only the last value stored in the array, it is for some reason overlapping the values that need to be stored in a multidimensional array.

<?php 
$Vendor1 = [];
$Vendor2 = [];
    
$OrderCode = $_POST['OrderCode'];
$OrderType = $_POST['OrderType'];
$OrderAmount = $_POST['OrderAmount'];

for ($i=0; $i<count($OrderCode); $i++)
{
    
if ($OrderType[$i] == "V1")  { $Vendor1[] = array("OrderCode" => $OrderCode[$i], "OrderAmount" => $OrderAmount[$i], "OrderType" => $OrderType[$i]) ; }

if ($OrderType[$i] == "V2")  { $Cheetay[] = array("OrderCode" => $OrderCode[$i], "OrderAmount" => $OrderAmount[$i], "OrderType" => $OrderType[$i]) ; }
}


foreach($Vendor1 as $key => $value)
        {
        echo $key." - ".$value;
    }


?>

The Output I am getting is 0 – Array 1 – Array and so on … not the actual values that should have been stored. Please help me to fix my mistake !

Advertisement

Answer

//Option 1 :
foreach($Vendor1 as $key => $value) {
  echo $key." - ".print_r($value, TRUE);
  echo "Key : " . $key . "<be>";
  foreach($value as $key2 => $value2) { //iterate $value again to get the array values
     echo "Innser Loop Key : " . $key2 . " - " . $value2 . "<pre>";
   }
}
//Option 2 : Get your array values by array key. Recommended.
foreach($Vendor1 as $key => $value) {
//get your array values by array key
echo "OrderCode" . $value['OrderCode'];
echo "OrderAmount" . $value['OrderAmount'];
echo "OrderType" . $value['OrderType'];
}

Feel free to ask if have any issues.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement