Jump to content

Shocked while trying to sort a simple array


adrianTNT

Recommended Posts

Hello. I was trying to sort values of an array and something is very different from everything I knew so far.

 

Code is:

$files_list = array();
array_push($files_list,"0.jpg");
array_push($files_list,"3.jpg");
array_push($files_list,"1.jpg");
array_push($files_list,"2.jpg");

arsort($files_list);

echo $files_list[0];

 

I was expecting last line to echo "3.jpg" but it keeps returning "0.jpg"  :o, I tried all kind of sort/arsort, nothing retruns that greatest value, what am I doing wrong?

I managed to find a solution by end($array_name), but still what was wrong with the above code?  :o

Link to comment
Share on other sites

Note: It seems you've solve this already but I typed a reply so I'm going to post it!  :shy:

 

arsort won't help you because although it does sort the items, the keys are preserved meaning that (as you can see) index zero still belongs with the value 0.jpg. sort won't help because it does re-index the array but sorts in ascending order.  What you're probably after is rsort (rsort($files_list, SORT_NUMERIC);). With that, the sorted $files_list[0] will be 3.jpg.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.