0

I want to use a multidimensional array in different functions.so i am making it as a global variable(array).i created a multidimensional array and made it as global to access in different function.now how can i get the values from it using foreach loop? here is my code

$test=array(
       array(
        "input1"=>"v1",
        "input2"=>"v2"),
        array(
         "input3"=>"v3",
         "input4"=>"v4")
      );

class testing
{
  function testp()
  {
    global $test;
    foreach($test as $key => $value)
    {
      echo $value;
    }
    var_dump($test);
    echo is_array($test);
  }
}

$obj = new testing();
$obj->testp();

i used is_array and var_dump to confirm whether its an array. all are fine and its shwoing Error suppression ignored. now how can i get the values from it?

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
sun
  • 1,598
  • 11
  • 26
  • 45
  • Indent that horrible code :) – Alvaro May 03 '13 at 10:29
  • Possible duplicates for http://stackoverflow.com/questions/10811908/find-values-in-multidimensional-arrays – Vijaya Pandey May 03 '13 at 10:29
  • 1
    Although not what you're asking for (sashkello covered that just fine) I highly recommend you get rid of the use of global and instead 'set' the array using a setter object method: function setData( array $data ) { $this->_data = $data; } .. you'll realize why once the app get bigger and your code is ridden with globals. – smassey May 03 '13 at 10:31

3 Answers3

3

It is array of arrays, what works for top order array, works further as well:

foreach($test as $key => $value)
{
   foreach($value as $k => $v){
      echo $v;
   }
}

This will echo your values v1, v2, v3, v4 one after another.

sashkello
  • 17,306
  • 24
  • 81
  • 109
1

More general answer:

public function visitArray($test)
{
  foreach($test as $key=>$value)
  {
    if(is_array($value))
    {
      visitArray($value);
    }
    else
    {
      echo $value;
    }
  }
}

Edit

Don't know why you're looping over keys and values, if key isn't took into account

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
1

More easy & simple way to access array values within a array.

foreach($test as $array_value){

    if(is_array($array_value)) {
        foreach ($array_value as $value) {
             echo $value.'<br>';
        }
      }
    }
Suresh Sapkota
  • 149
  • 3
  • 7