-4

I've got something but still it isn't working like I want it to work.

I've got an array

    $values = array(
    $aV=>$aP, 
    $bV=>$bP, 
    $cV=>$cP, 
    $dV=>$dP
);

then I sort it like this ` arsort($values);

the result is Array ( [geel] => 28 [groen] => 20 [rood] => 20 [blauw] => 12 )

Now I want to acces the first / second / tird / fourth element to pass it on So I want $values[0] to be the first element. In this case Geel 28. But if I try to echo $values[0] it says Undefined offset: 0 (same with 1/2/3 etc). Obviously because I've got no [0] set but how can I set [0] to the first element in the array (which is different each time. the value geel isn't always [0] but I need the first element (with the lowest number) to be [0] so I can echo $values[0] to be the first element of the array with the lowest number

Cœur
  • 37,241
  • 25
  • 195
  • 267
answer_me
  • 3
  • 6

4 Answers4

1

If you need access to the index and the value of your array, then a foreach loop can do that for you

$values = array($aV=>$aP,  $bV=>$bP,  $cV=>$cP, $dV=>$dP );

foreach ( $values as $idx => $val ) {
    echo "Index is $idx and value is $val";
}

With this array you gave as an example

Array ( [geel] => 28 [groen] => 20 [rood] => 20 [blauw] => 12 )

the output would be

Index is geel and value is 28
Index is groen and value is 20
Index is rood and value is 20
Index is blauw and value is 12
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

Because array key has been set as geel, groen..you can not access like $values[0],$values[1].

You must access like:

First element: $values['geel'] Second element: $values['groen'] etc....

Jayesh Chitroda
  • 4,987
  • 13
  • 18
  • I know. I updated my question. But how can I acces the first element of the array as `[0]`. because 'geel' 'groen' etc aren't always in the same position of the array. I need to call the first element , second etc wich are all different everytime – answer_me May 17 '16 at 11:23
  • simply go with #splash58 in your post comment – Murad Hasan May 17 '16 at 11:24
0

For accessing both values and keys as numeric index you need to use array_values and array_keys

Array:

$values = array(
    $aV=>$aP, 
    $bV=>$bP, 
    $cV=>$cP, 
    $dV=>$dP
);

For the values:

$new_values = array_values($values);

Result:

array($aP, $bP, $cP, $dP);

For the keys:

$keys = array_keys($values);

Result:

array($aV, $bV, $cV, $dV);

Now you can access both the array as numeric keys like: $keys[0] or $new_values[0] and so on.

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
-1

Don't use the "arrow" indicator to make your arrays, you're probably looking to do this:

$values = array(
    $aV . ' ' . $aP,
    $bV . ' ' . $bP,
    $cV . ' ' . $cP,
    $dV . ' ' . $dP,
);

What you're currently doing is creating an array that looks like this

[
    'Geel' => 28
    // etc.
]

If you really just wanted to get the value of the first element you could use array_shift

Kalkran
  • 324
  • 1
  • 8