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?

3
  • Indent that horrible code :) Commented May 3, 2013 at 10:29
  • Possible duplicates for stackoverflow.com/questions/10811908/… Commented May 3, 2013 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. Commented May 3, 2013 at 10:31

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Fine.Now how can i get values upto v3 not v4?
@raj, just make a counter which will break out of loop on 3.
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

Comments

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>';
        }
      }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.