Oihana PHP

reorder.php

Table of Contents

Functions

reorder()  : array<string|int, mixed>
Reorders an associative array by placing specified keys first, optionally sorting the rest.

Functions

reorder()

Reorders an associative array by placing specified keys first, optionally sorting the rest.

reorder(array<string|int, mixed> $array[, array<string|int, string> $firstKeys = [] ][, bool $sort = true ]) : array<string|int, mixed>

This function is useful for JSON serialization where key order matters (e.g., @type, @context first).

Parameters
$array : array<string|int, mixed>

The input associative array.

$firstKeys : array<string|int, string> = []

Keys that should appear first, in the given order.

$sort : bool = true

Whether to sort remaining keys alphabetically (default: true).

Tags
example

Basic reordering

$data = ['name' => 'Alice', 'id' => 1, 'type' => 'User'];
$result = reorder($data, ['type', 'id']);
// ['type' => 'User', 'id' => 1, 'name' => 'Alice']
example

With alphabetical sorting

$data = ['z' => 1, 'a' => 2, 'type' => 3];
$result = reorder($data, ['type'], true);
// ['type' => 3, 'a' => 2, 'z' => 1]
example

Non-existent keys are ignored

$data = ['name' => 'Bob'];
$result = reorder($data, ['id', 'name']);
// ['name' => 'Bob'] (id doesn't exist, so it's skipped)
author

Marc Alcaraz

since
1.0.8
Return values
array<string|int, mixed>

The reordered array.


        
On this page

Search results