Home > Software design >  PHP - Array For Loop Not Storing Values
PHP - Array For Loop Not Storing Values

Time:07-02

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 !

CodePudding user response:

"$value" is an array.

If you echo an array, you get "Array".

If you change "$value" to "print_r($value, TRUE)" then you should see the contents printed.

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

That, or loop over $value like you are doing with $Vendor1.

CodePudding user response:

//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.

  • Related