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

146 views Asked by At

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!

3

There are 3 answers

0
SERPRO On BEST ANSWER

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;
}
0
Sabari On

You can do it in nested foreach loops. This will be easy instead of going for two for loops seperatley

foreach ($jabroni as $keys => $values)
{
    if ($keys == 'phrases' || $keys == 'moves') {
           foreach ($values as $value) {
             echo $value;
           }
    }
}
1
Dogbert On
foreach ($jabroni->phrases as $value) {
    echo $value;
}

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