1

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!

Manse
  • 37,765
  • 10
  • 83
  • 108
tomaytotomato
  • 3,788
  • 16
  • 64
  • 119

3 Answers3

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

foreach ($jabroni->moves as $value) {
    echo $value;
}
Dogbert
  • 212,659
  • 41
  • 396
  • 397
2

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;
}
SERPRO
  • 10,015
  • 8
  • 46
  • 63
1

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;
           }
    }
}
Sabari
  • 6,205
  • 1
  • 27
  • 36