Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP natsort() not sorting my URLs as I think it should

I am trying to sort image URLs and send back the image which is alphabetically first to show as featured image. Here is the code I have so far:

$image_array = get_post_meta($postID, "image_array", true);
$thumbnail_array = array();
    for ($i = 0; $i < count($image_array ); $i++) {
        $thumbnail_array[] = $image_array [$i]['thumbnail'];
    }
    natsort($thumbnail_array);
    return $thumbnail_array[0];

First I retrieve the array of images which is a json file, then I put each thumbnail URL in a thumbnail_array which is then sorted and returned. This doesn’t seem to work however, I tried to log $thumbnail_array[0] and $thumbnail_array[1] before and after the sorting and here is what I got as an example:

Before natsort:
[0]: https://example.com/staging/wp-content/uploads/2022/08/image2-263x350.jpeg
[1]: https://example.com/staging/wp-content/uploads/2022/08/image1-263x350.jpeg

After natsort: 
[0]: https://example.com/staging/wp-content/uploads/2022/08/image2-263x350.jpeg
[1]: https://example.com/staging/wp-content/uploads/2022/08/image1-263x350.jpeg

Nothing happens after the sort, shouldn’t 1 come before 2? Why is this? Am I missing something obvious (probably yes)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

natsort retains key-value association:

$a = [
    'https://example.com/staging/wp-content/uploads/2022/08/image2-263x350.jpeg',
    'https://example.com/staging/wp-content/uploads/2022/08/image1-263x350.jpeg'
];

natsort($a);
var_dump($a);
array(2) {
  [1]=>
  string(74) "https://example.com/staging/wp-content/uploads/2022/08/image1-263x350.jpeg"
  [0]=>
  string(74) "https://example.com/staging/wp-content/uploads/2022/08/image2-263x350.jpeg"
}

So yes, 0 will still be the 0 value and so on, but their order changed within the array. You can reset the keys if you want to renumber the values:

natsort($thumbnail_array);
$thumbnail_array = array_values($thumbnail_array);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading