Reply to Re: Numerically Indexed Arrays...Out of order???

Your name:

Reply:


Posted by Rik Wasmus on 12/08/07 11:56

On Sat, 08 Dec 2007 12:36:41 +0100, kaydubbleu <kevwilliams@gmail.com> =

wrote:

> I have found that when inserting elements into an array they stay in
> the same order they are inserted, even when using numerical keys.
>
> Example:
> $a =3D array(4=3D>'Four',1=3D>'One',5=3D>'Five',2=3D>'Two',3=3D>'Three=
');
> print_r($a);
>
> Ouptuts:
> Array
> (
> [4] =3D> Four
> [1] =3D> One
> [5] =3D> Five
> [2] =3D> Two
> [3] =3D> Three
> )
>
> The only way to get them into proper order is to use ksort(). I am not=

> sure why this is desired functionality. If someone could please
> explain I would love to know..

Why should they be automatically ordered by numerical key? Numerically =

indexed does not mean that automatically. You control the order, so if y=
ou =

put them in a different one, who is PHP to say you're wrong? If you want=
=

them ordered by something, one of the sorting/splicing functions is the =
=

way to go.

Another problem which would arise, is a mixed array: If you think they =

should be in order, should numerical keys be automaically sorted, and =

strings not? What about strings which happened to be interpretable as =

integer?

Some food for thought:
<?php
$arr =3D array('3' =3D> 'foo', 3 =3D>'bar',4 =3D> 'foz','4'=3D> 'baz' );=

var_dump($arr);
foreach($arr as $k =3D> $v){
echo "key:\n";
var_dump($k);
echo "value:\n";
var_dump($v);
}
?>

array(2) {
[3]=3D>
string(3) "bar"
[4]=3D>
string(3) "baz"
}
key:
int(3)
value:
string(3) "bar"
key:
int(4)
value:
string(3) "baz"
-- =

Rik Wasmus

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация