Re: getting the "next" element of an associative array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Olav Mørkrid wrote:
let's say we have the following associative array:

$array = array(
 "red" => "ferrari",
 "yellow" => "volkswagen",
 "green" => "mercedes",
 "blue" => "volvo"
);

then we have a current index into the array:

$index = "yellow";
$current = $array[$index];

now: how do i get the key of the next array element (in this case "green")?

$next = ?

Give this a shot

<?php

function array_next($ar, $curr) {
	$capture = false;
	$next = '';
	foreach ( $ar AS $k => $v ) {
		if ( $capture ) {
			return array($k => $v);
		}
		if ( $k == $curr ) {
			$capture = true;
		}
	}
	return $next;
}


$array = array(
 "red" => "ferrari",
 "yellow" => "volkswagen",
 "green" => "mercedes",
 "blue" => "volvo"
);

print_r( array_next($array, 'yellow') );

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux