Re: difference between indexed and associative arrays?

From: Date: Wed, 05 Apr 2017 16:46:16 +0000
Subject: Re: difference between indexed and associative arrays?
References: 1 2 3 4  Groups: php.general 
Request: Send a blank email to php-general+get-326057@lists.php.net to get a copy of this message
On 05.04.2017 at 16:23, Larry Garfield wrote: > On 04/04/2017 06:23 PM, Jeffry Killen wrote: > >> And associative array would be looped with foreach >> and an indexed array would be looped through with for and an iterator. > > Untrue. foreach() works just fine with both types of arrays. > > Strictly speaking PHP doesn't have indexed arrays. It has an ordered > hash, which it calls an array, which has some special magic in it that > gives it a monotonically increasing integer key if one is not specified, > allowing it to behave kinda like an arbitrarily sized array. There is > no difference in the data structure itself. > > $arr = ['A', 'B', 'C']; > > foreach ($arr as $val) { > print $val . PHP_EOL; > } > > That's totally legit. Indeed. And if you need also the numeric index, you could do: foreach ($arr as $i => $val) { print "$i: $val\n"; } > I honestly don't recall the last time I used a > for() loop in PHP. :-) I usually prefer foreach loops as well, but there is at least one case where a for loop might be preferable, namely if there are a certain number of runs and range() would be unnecessary overhead. -- Christoph M. Becker

« previous php.general (#326057) next »