Return first n values of associative PHP array?

150

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

49

Answer

Solution:

You need to usearray_slice() for slice your array at a fixed length and then usearray_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 thearray_keys:

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

Remember to usetrue when you don't use thearray_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.

Updates:

As you are asking for only the array keys, By default array_slice reset the array keys, if you want to preserve then you need to use true as the forth parameter of array_slice.

$new_arr = array_slice($engagement, $start, $length, true);
$keys = array_keys($new_arr); // here is the list of the keys
876

Answer

Solution:

try something like this ...

$test = array('29.58', '21.78', '56.258', '10.145', '98.23', '20', '78.32', '112', '5.64', '55.26');
asort($test);

$count = 0;
foreach($test as $key => $val)
{
    if($count <=5)
    {
        echo " [".$key."] => ".$val."\t";
        $count+=1;
    }
}

People are also looking for solutions to the problem: javascript - How to create a clickable html table with php?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.