0

Is possible to loop trough an array in php like we do it in JavaScript for example without using the for ( $X as $Y){}

For example we in JavaScript we can use this code :

var names=['john','tom','jane'];

for (i=0;i<names.length;i++){
        names[i];
 }

Now in the case of using the same method for this loop it would be this one and it gives us an error :

$names=['john','tom','jane'];
    for ($i=0;$i<$names.length;$i++){
        $names[$i];
    }

So is there a way around this?

Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46

2 Answers2

1

You can use count() for the length of the array.

$names = ['john', 'tom', 'jane'];

for ($i=0; $i < count($names); $i++){
  echo $names[$i];
}
Edward
  • 4,887
  • 3
  • 17
  • 25
0

First of all the code gives you errors because you have written lenght wrong. It should be sizeof() or count().Secondly there is also another option for looping through array. That’s foreach. As I’m not on the computer you could check out the php manual for foreach and how to use it. I hope I was useful !