Question

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!

Was it helpful?

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

OTHER TIPS

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

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

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;
           }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top