Jump to content

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);
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.