Re: Finding next recored in a array

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

 



On Sun, Sep 16, 2007 at 07:09:02PM -0400, brian wrote:
> Richard Kurth wrote:
>> $Campaign_array| = array('0','1','3','5','8','15','25');|
>> I know that I can find the next recored in a array using next. What I do 
>> not understand is if I know the last number was say 5 how do I tell the 
>> script that that is the current number so I can select the next  record
>> ||
>
> I think you'll need your own function for this.

Nope. Just use array_search().

$k = array_search('5',$Campaign_array);
if ($k + 1 > count($Campaign_array)) { echo $Campaign_array[$k + 1]; }

> Pass in the array and loop 
> through it until you find the key, increment that, ensure that there is 
> another value with that key, and return the key (or the value).
>
> (untested)
>
> function nextInArray($arr, $val)
> {
> 	$next_key = NULL;
>
> 	for ($i = 0; $i < sizeof($arr);$i++)
> 	{
> 		if ($arr[$i] == $val)
> 		{
> 			$next_key = ++$i;
> 			break;
> 		}
> 	}
>
> 	// return the key:
> 	return (array_key_exists($next_key) ? $next_key : NULL);
>
> 	// or the value:
> 	return (array_key_exists($next_key) ? $arr[$next_key] : NULL);
>
> }
>
> However, in your example, you're searching for the key that points to the 
> value '5'. What if the value '5' occurs more than once?

>From the docs:

"If needle is found in haystack more than once, the first matching key
is returned. To return the keys for all matching values, use
array_keys() with the optional search_value parameter instead."

-- 
"Now what liberty can there be where property is taken without consent??"
	--  Samuel Adams
    Rick Pasotto    rick@xxxxxxxx    http://www.niof.net

-- 
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