Search code examples
phpobjectforeachmember-variables

How to foreach through part of an objects member variables that are arrays?


I am trying to create a foreach that will go through some variables within an object.

At the moment it is just

class jabroni
{
  var $name = "The Rock";
  var $phrases = array ("The rock says", "Im gonna put the smackdown on you", "Bring it on jabroni");
  var $moves = array ("Clothes line", "Pile driver", "Reverse flip");
}

I tried doing this:

$jabroni = new jabroni()
foreach ($jabroni as $value)
{
  echo $value->phrases;
  echo $value->moves;
}

However nothing gets printed.

Any ideas if what I am trying to achieve is possible, I have that gut feeling that its not and that I will have to just do individual foreach statements for each object member variable that is an area?

Thanks for your time!


Solution

  • You are doing wrong the loop.. You have one object, not an array of objects. so the correct way should be..

    $jabroni = new jabroni();
    foreach ($jabroni->phrases as $value)
    {
        echo $value;
    }
    foreach ($jabroni->moves as $value)
    {
        echo $value;
    }