Skip to content

PHP array functions API

PHP's built-in array functions — PHP arrays serve as both lists and ordered maps.

1 class · 7 methods

array functions

7 methods

Procedural array functions for manipulating PHP's versatile array type.

array_push(array &$array, mixed ...$values): int

Pushes one or more elements onto the end of array. Returns the new number of elements.

Parameters

NameTypeDescription
arrayarrayInput array (passed by reference).
valuesmixedValues to push.

Returns

int

Example

php
<?php
$arr = [1, 2];
$n = array_push($arr, 3, 4);
// $arr == [1, 2, 3, 4], $n == 4
array_pop(array &$array): mixed|null

Pops and returns the last value of the array, shortening it by one element.

Parameters

NameTypeDescription
arrayarrayInput array (passed by reference).

Returns

mixed|null

Example

php
<?php
$arr = [1, 2, 3];
$v = array_pop($arr);
// $v == 3, $arr == [1, 2]
count(Countable|array $value, int $mode = COUNT_NORMAL): int

Counts all elements in an array or Countable object.

Parameters

NameTypeDescription
valueCountable|arrayArray or Countable object.
modeintCOUNT_RECURSIVE to count multidimensional arrays.

Returns

int

Example

php
<?php
$arr = [1, 2, 3];
echo count($arr);  // 3
array_map(?callable $callback, array $array, array ...$arrays): array

Applies the callback to the elements of the given arrays and returns a new array.

Parameters

NameTypeDescription
callback?callableFunction to apply (null = array of values).
arrayarrayInput array.

Returns

array

Example

php
<?php
$squares = array_map(fn($x) => $x * $x, [1, 2, 3]);
// [1, 4, 9]
array_filter(array $array, ?callable $callback = null, int $mode = 0): array

Filters elements of an array using a callback. Without a callback, removes falsy values.

Parameters

NameTypeDescription
arrayarrayInput array.
callback?callablePredicate (default removes falsy values).

Returns

array

Example

php
<?php
$evens = array_filter([1, 2, 3, 4], fn($x) => $x % 2 === 0);
// [1 => 2, 3 => 4]  (keys preserved)
array_merge(array ...$arrays): array

Merges the elements of one or more arrays together. Re-indexes numeric keys.

Parameters

NameTypeDescription
arraysarrayArrays to merge.

Returns

array

Example

php
<?php
$r = array_merge([1, 2], [3, 4]);
// [1, 2, 3, 4]
$m = array_merge(["a" => 1], ["a" => 2, "b" => 3]);
// ["a" => 2, "b" => 3]
in_array(mixed $needle, array $haystack, bool $strict = false): bool

Checks if a value exists in an array. Use strict=true for type-safe comparison.

Parameters

NameTypeDescription
needlemixedValue to search for.
haystackarrayArray to search.
strictboolIf true, uses === comparison.

Returns

bool

Example

php
<?php
$ok = in_array(2, [1, 2, 3]);        // true
$ok2 = in_array("2", [1, 2, 3], true); // false (strict)