Jump to content

point to next array element


hansford

Recommended Posts

Given the following example code; if a function were passed the value of $id is there a way to point to the previous or next element in the array to retrieve their values.

 

thanks

 

 


$arr = array();

for( $i = 0; $i < 10; $i++ ) {

$id = mt_rand() + $i;

$arr[$id] = "some value";

}

function getValue( $id ) {

$element = $arr[$id];

//point to previous element or next element beginning from $element position

}

Link to comment
https://forums.phpfreaks.com/topic/232045-point-to-next-array-element/
Share on other sites

I figured it out by trial and error. Here is what I did.

 


function getValue( $id ) {

$element = $arr[$id];
--$arg[$id];
extract( $arg );
$element = current( $arg );
extract( $element );
echo $id;  //displays previous elements id;
$element = next( $arg );
	extract( $element );
	return $id;

}

Sorry guys, here's the exact code;

 

function showValue( $id ) {

	global $arg;
	--$arg[$id];
	extract( $arg );
	$element = current( $arg );
	extract( $element );
	$element = next( $arg );
	echo $id . '<br />';  //displays previous elements id;
	extract( $element );
	echo $id . '<br />';  //displays next elements id;

}

try

<?php

$arr = array();

for ($i = 0; $i < 10; $i++) {

    $id = mt_rand() + $i;

    $arr[$id] = "some value $i";
}
echo '<pre>', print_r($arr), "</pre>\n";
$id = array_rand($arr);
echo "Srch element with key $id and value {$arr[$id]}<hr />\n";

function getValue($id, $arr) {
    end($arr);
    if ($id == key($arr)) $is_last = true;
    reset($arr);
    if ($id == key($arr)) $is_first = true;
    while (key($arr) != $id) next($arr);
    if ($is_last) echo "No next elemenrt.<br />\n";
    else {
        next($arr);
        echo "Next element with key ", key($arr), " is '", current($arr), "'<br />\n";
        prev($arr);
    }
    if($is_first) echo "No prev element";
    prev($arr);
    echo "Prev element with key ", key($arr), " is '", current($arr), "'<br />\n";
}

getValue($id, $arr);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.