SanJeet Singh SanJeet Singh - 5 months ago 16
PHP Question

Print first n values of a sorted associative PHP array with numbers and floats?

I have a PHP array which after sorting looks like:

Array ( [542] => 30 [588] => 29.77 [409] => 19.9 [237] => 19.47 [457] => 17.73 [410] => 15.86);


The actual array is quite long. Initially, the keys were set sequentially like 0, 1, 2...
Then I sorted the array and now the array looks like the array above. When I tried to print the first element if this sorted array using echo
$engagement[0]
, I did not get the value 30. To get 30 I had to use
$engagement[542]
. But I have no way of knowing what might be the first key in this sorted array. How can I print first n key and value pairs of this sorted array?

Let me know if I need to be more clear with my explanation. :)

Answer

You need to use array_slice() for slice your array at a fixed length and then use array_keys.

$length = 50;
$start = 0;
$new_arr = array_slice($engagement, $start, $length);
$keys = array_keys($new_arr);
foreach($keys as $key){
    echo $new_arr[$keys[$key]];
}

Without the array_keys:

foreach($new_arr as $key => $value){
    echo $key." => ".$value;
}

Remember to use true when you don't use the array_keys like:

$new_arr = array_slice($engagement, $start, $length, true);

More about: array_slice

If you don't use the true the slice array index will be reset and you lose the keys.