0

So I've been pulling my hair trying to figure out why the output is showing an Array text instead of displaying the actual values. Below is an array that I'm trying to fetch the values.

array(4) {
  [0]=>
  array(3) {
    [0]=>
    string(6) "400 ml"
    [1]=>
    string(2) "1L"
    [2]=>
    string(2) "2L"
  }
  [1]=>
  array(8) {
    [0]=>
    string(17) "100% Orange Juice"
    [1]=>
    string(5) "Apple"
    [2]=>
    string(4) "Pear"
    [3]=>
    string(9) "Pineapple"
    [4]=>
    string(12) "Passionfruit"
    [5]=>
    string(15) "Red Dragonfruit"
    [6]=>
    string(13) "Baobab Powder"
    [7]=>
    string(17) "Grapeseed Extract"
  }
  [2]=>
  array(1) {
    [0]=>
    string(3) "Yes"
  }
  [3]=>
  array(1) {
    [0]=>
    string(3) "Yes"
  }
}

If I tried looping through it using foreach it gives me the output Array Array Array Array

foreach($singleArray as $key => $val) {
    echo $val; 
}

If I tried specifying the index like below, it gives me the actual values

foreach($singleArray[0] as $key => $val) {
    echo $val; 
}
clestcruz
  • 1,081
  • 3
  • 31
  • 75
  • 3
    That's because in your first loop `$val` is an array, and when you `echo` an array you get `Array`. You can replace `echo $val` with `print_r($val)` (or `var_dump`, or `var_export`) or you can use a nested foreach loop `foreach($singleArray as $val) { foreach ($val as $v) { echo $v; }}` – Nick Sep 02 '20 at 12:34
  • 2
    So basically I should do another `foreach`? – clestcruz Sep 02 '20 at 12:36
  • 1
    yes, that would be the simplest, as I described in the comment – Nick Sep 02 '20 at 12:36
  • My objective is actually fetch all the values in the array and store it in a single array – clestcruz Sep 02 '20 at 12:43
  • That sounds like you want to flatten the array. Take a look at https://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array and https://stackoverflow.com/questions/526556/how-to-flatten-a-multi-dimensional-array-to-simple-one-in-php – Nick Sep 02 '20 at 12:45

0 Answers0