Quote:
Originally Posted by sonic656
Code:
var names = ["Chris", "Kate", "Steve"]; //some values
for(var i in names) {alert(names[i]);}
Hi. This is script that I use in JavaScript. I need to get it working in PHP.
|
I might note that the for...in loop in JavaScript is used to loop over the enumerable properties of an object. for looping over an array either use a standard for() loop or the array’s forEach() method.
example where for...in and for() have a different behaviour:
PHP Code:
var names = ["Chris", "Kate", "Steve"];
names["John"] = "Doe"; // looks like an associative array? it does, but an associative array does not exist in JS, you’re just extending your array object
var count = 0;
for (var i = names.length; i--;) {
count++;
}
alert(count); // 3
count = 0;
for (var j in names) {
count++;
}
alert(count); // 4
in case of PHP, the standard array is something completely different to a JavaScript array (the closest would be the SplFixedArray object), but yes, foreach() would be the structure to go. esp. since foreach() (PHP) is almost equivalent to JavaScripts for...in and for each...in. PHP’s foreach() is also able to loop over object properties and Iterator objects.