Oihana PHP

swap.php

Table of Contents

Functions

swap()  : array<string|int, mixed>
Swaps two indexed values in a specific array representation.

Functions

swap()

Swaps two indexed values in a specific array representation.

swap(array<string|int, mixed> $ar[, int|string $from = 0 ][, int|string $to = 0 ][, bool $copy = false ]) : array<string|int, mixed>

Supports both integer and string keys. Negative indices are supported to count from the end (e.g. -1 is the last element).

If $copy is true, returns a new array with swapped values, leaving original intact. Otherwise, swaps values directly on the passed array.

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

The array of values to change

$from : int|string = 0

The first key/index position to swap (default: 0)

$to : int|string = 0

The second key/index position to swap (default: 0)

$copy : bool = false

If true, returns a swapped clone of the passed-in array (default: false)

Tags
example
$ar = [1, 2, 3, 4];
swap($ar, 1, 3);
print_r($ar); // [1, 4, 3, 2]

$arAssoc = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$swapped = swap($arAssoc, 'a', 'c', true);
print_r($swapped); // ['c' => 'cherry', 'b' => 'banana', 'a' => 'apple']
author

Marc Alcaraz (ekameleon)

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

The modified array reference.


        
On this page

Search results