How to get the i'th element of an associative array?

710 views Asked by At

I have the array:

array(2=>'0',3=>'1',5=>'3',4=>'4',7=>'2')

Note: Nothing seems to be in order. So leave the plan to find a numeric order.

How can I fixed the i'th element of this associative array?

For example when i is 4 the value should be 4, when i is 1 the value should be 0.

array_shift() never solves this requirement. Knowing very well that the logic of looping solves this problem.

3

There are 3 answers

0
Rizier123 On BEST ANSWER

This should work for you:

Here you just can use array_keys() to access the keys of your associative array as a numerical indexed array, which you then again can use as key for the array.

$arr = array(2=>'0',3=>'1',5=>'3',4=>'4',7=>'2');
echo $arr[array_keys($arr)[3]];
                         //^ This is your 'i'

output:

4

when the solution is a[i] <- You can't get it that simple, but you get close with the solution above. (Note, that since the array with the keys is 0-based index, the 4th element is index 3)

You can use a variable and then subtract one, to get your logic, that 4 => 4.

$i = 4;
$arr = array(2=>'0',3=>'1',5=>'3',4=>'4',7=>'2');
echo $arr[array_keys($arr)[$i-1]];
1
Sanjay Kumar N S On

Try this:

$arr1 = array(2=>'0',3=>'1',5=>'3',4=>'4',7=>'2');
$i=0;
$findIndex = 4;
$value = '';
foreach($arr1 AS $ele) {
    if ($findIndex == $i) {
        $value = $ele;
        break;
    }
    $i++;
}
echo $value ? $value : 'Not found';
0
splash58 On

Without function call, maybe, faster

$arr = array(2=>'0',3=>'1',5=>'3',4=>'4',7=>'2');
$i = 4;
foreach($arr as $v) 
   if(!--$i) { echo $v; break; }