PHP array_multisort fails in PHP 8, works in PHP 7.4

✔ Recommended Answer

You seem to have the arrays backwards. The first array is what is actually sorted, and the second array has the same transformation applied to it.

array_multisort(    array_map(fn($page) => preg_replace('_^[^0-9a-z]*_', '', strtolower($page['title'])), $pages),    SORT_ASC, SORT_STRING,    $pages);

Source: stackoverflow.com

Answered By: Sammitch

Method #2

array_multisort has undergone some changes in PHP 8. One of the changes is that the function no longer accepts null values. If you try to pass a null value as one of the arguments, it will trigger a TypeError.

Here's an example of how to fix the issue:

php
// Example data $data = [ ['id' => 1, 'name' => 'John', 'age' => 30], ['id' => 2, 'name' => 'Mary', 'age' => 25], ['id' => 3, 'name' => 'Bob', 'age' => null], ]; // Create a separate array of ages to sort by $ages = array_column($data, 'age'); // Replace null values with a placeholder value that can be sorted foreach ($ages as $key => $value) { if ($value === null) { $ages[$key] = -1; // Replace with a negative number or any other placeholder value } } // Sort the data by age array_multisort($ages, SORT_DESC, $data); // Replace the placeholder value with null again foreach ($ages as $key => $value) { if ($value === -1) { $data[$key]['age'] = null; } } // Print the sorted data print_r($data);

In this example, we first create a separate array of ages to sort by using array_column(). Then, we replace any null values in the ages array with a placeholder value (in this case, -1). We sort the data using array_multisort(), and then replace the placeholder value with null again. Finally, we print the sorted data.

By replacing null values with a placeholder value before sorting, we can avoid triggering the TypeError in PHP 8.

Comments

Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755