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