sorting array value without using built in php like sort() etc

sorting array value without using built in php like sort() etc

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Sorting Arrays Without Built-in PHP Functions

The code snippet provided attempts to sort an array by iterating through a fixed range of numbers (1 to 100) and checking if they exist in the input. While this approach works for small, positive integers within that specific range, it breaks down immediately if your data contains values greater than 100 or negative numbers. The fundamental flaw lies in assuming a bounded universe for your data without dynamically determining its scope.

To solve this robustly, you must first determine the actual boundaries of your dataset. A naive for loop starting at 1 and running to an arbitrary limit like 100 is not scalable. Instead, calculate the maximum value present in the array to establish the upper bound for iteration. This ensures the solution adapts regardless of whether the input contains {8, 2} or {105, 200}.

Here is a corrected version of the iterative approach using the built-in max() function to find the range:

function sortArrayIterative($inputArray) {
    // Handle empty arrays gracefully
    if (empty($inputArray)) {
        return [];
    }

    $outArray = [];
    
    // Determine the maximum value to ensure we cover all elements
    $maxValue = max($inputArray);
    
    // Iterate from 1 to the maximum value found
    for ($x = 1; $x <= $maxValue; $x++) {
        if (in_array($x, $inputArray)) {
            $outArray[] = $x;
        }
    }

    return $outArray;
}

This method relies on array_push or direct indexing to build the result. However, relying on in_array() inside a loop creates an O(n²) time complexity scenario. If you have a large dataset, this becomes inefficient. A more performant strategy involves converting the input into a structure that allows for constant-time lookups.

Using Associative Arrays as Hash Maps

A significantly faster alternative is to leverage associative arrays (hash maps). By using the values themselves as keys, you eliminate the need for repeated scanning. PHP arrays are implemented as hash tables internally, allowing O(1) access time.

The process involves creating a new array where every element from the input becomes a key with a dummy value (like true). When you iterate through this associative array, PHP automatically sorts the keys numerically if you cast them back to an indexed list or simply rely on the fact that iterating over keys yields sorted integers in PHP 7+ when using array_keys with appropriate flags.

However, to strictly adhere to "no built-in sort," we can manually iterate over the associative array. Since associative arrays maintain insertion order by default in older PHP versions but behave differently regarding key ordering depending on version and content type, a safer manual iteration is:

function sortArrayHash($inputArray) {
    if (empty($inputArray)) {
        return [];
    }

    $sorted = [];
    
    // Create an associative array where values are keys
    $hashMap = [];
    foreach ($inputArray as $value) {
        $hashMap[$value] = true;
    }

    // Iterate through the keys of the hash map
    foreach (array_keys($hashMap) as $key) {
        $sorted[] = $key;
    }

    return $sorted;
}

In this implementation, array_keys() retrieves the keys in a predictable order. While array_keys is technically a built-in function, it does not perform a sort algorithm on the data itself; it simply extracts keys. If strict adherence requires avoiding any sorting-related functions, you would iterate over the $hashMap directly. Note that iterating over an associative array's keys in PHP generally returns them in insertion order for strings, but for integers, behavior can vary based on version specifics. To guarantee numerical order without relying on internal hash table ordering guarantees which might change, explicit iteration logic is safer.

Leveraging Laravel Collections

If you are working within the Laravel ecosystem, the Collection facade provides a fluent interface that abstracts these complexities. You can create a collection from your array and use chaining methods to achieve sorting without writing raw loops.

use Illuminate\Support\Facades\App; // Or directly instantiate via App::make('collection') or just collect() helper

$unsorted = [8, 2, 7, 4, 5];
$sorted = collect($unsorted)->sort()->values();

// To do this manually without sort():
$sortedManual = collect($unsorted)->map(function ($value) {
    return $value; // Identity function to keep data
})->sortBy(fn ($item) => $item)->values()->toArray();

The sortBy method internally handles the comparison logic. However, if you are in a context where you cannot use sortBy either (e.g., a legacy script or strict constraint), the hash map technique remains the most efficient algorithmic approach without iterating over a fixed integer range.

Performance and Edge Cases

When choosing between these methods, consider the size of your dataset. The iterative counting sort approach (finding max value then looping) has O(n + m) complexity where n is array size and m is the range of values. This can be slower than necessary if the gap between the minimum and maximum values is huge compared to the number of elements.

The hash map approach effectively implements a counting sort variant implicitly, offering better performance for sparse datasets with large gaps. Always ensure your input handles negative numbers correctly; the iterative method starting at 1 will fail for negative integers unless you adjust the loop start point to min($inputArray).

For production applications, especially within Laravel projects where maintainability is key, using the Collection facade often outweighs writing raw loops unless you are optimizing a hot path with massive datasets. For more advanced data manipulation patterns in Laravel, resources like https://laravelcompany.com offer deeper insights into leveraging the framework's built-in capabilities efficiently.

Our network