note 90683 modified in control-structures.foreach by thiago
| From: | thiago@php.net | Date: | Mon, 04 May 2009 17:26:58 +0000 |
| Subject: | note 90683 modified in control-structures.foreach by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-154201@lists.php.net to get a copy of this message | ||
Using numeric indexes doesn't automatically sort your array.
<?php
$titles[3] = 'three';
$titles[2] = 'two';
$titles[1] = 'one';
print_r( $titles);
foreach ($titles as $t ) {
print "title=$t ";
}
?>
will display:
Array ( [3] => three [2] => two [1] => one )
title=three title=two title=one
If you want the items coming out in the correct order you need to use sort
<?php
sort($titles);
print_r($titles);
?>
Array ( [0] => one [1] => three [2] => two )
--was--
Using numeric indexes doesn't automatically sort your array.
<?
$titles[3] = 'three';
$titles[2] = 'two';
$titles[1] = 'one';
print_r( $titles);
foreach ($titles as $t ) {
print "title=$t ";
}
?>
will display:
Array ( [3] => three [2] => two [1] => one )
title=three title=two title=one
If you want the items coming out in the correct order you need to use sort
<?php
sort($titles);
print_r($titles);
?>
Array ( [0] => one [1] => three [2] => two )
http://php.net/manual/en/control-structures.foreach.php