array functions
7 methodsProcedural array functions for manipulating PHP's versatile array type.
array_push(array &$array, mixed ...$values): intPushes one or more elements onto the end of array. Returns the new number of elements.
Parameters
| Name | Type | Description |
|---|---|---|
| array | array | Input array (passed by reference). |
| values | mixed | Values to push. |
Returns
int
Example
php
<?php
$arr = [1, 2];
$n = array_push($arr, 3, 4);
// $arr == [1, 2, 3, 4], $n == 4array_pop(array &$array): mixed|nullPops and returns the last value of the array, shortening it by one element.
Parameters
| Name | Type | Description |
|---|---|---|
| array | array | Input 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): intCounts all elements in an array or Countable object.
Parameters
| Name | Type | Description |
|---|---|---|
| value | Countable|array | Array or Countable object. |
| mode | int | COUNT_RECURSIVE to count multidimensional arrays. |
Returns
int
Example
php
<?php
$arr = [1, 2, 3];
echo count($arr); // 3array_map(?callable $callback, array $array, array ...$arrays): arrayApplies the callback to the elements of the given arrays and returns a new array.
Parameters
| Name | Type | Description |
|---|---|---|
| callback | ?callable | Function to apply (null = array of values). |
| array | array | Input 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): arrayFilters elements of an array using a callback. Without a callback, removes falsy values.
Parameters
| Name | Type | Description |
|---|---|---|
| array | array | Input array. |
| callback | ?callable | Predicate (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): arrayMerges the elements of one or more arrays together. Re-indexes numeric keys.
Parameters
| Name | Type | Description |
|---|---|---|
| arrays | array | Arrays 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): boolChecks if a value exists in an array. Use strict=true for type-safe comparison.
Parameters
| Name | Type | Description |
|---|---|---|
| needle | mixed | Value to search for. |
| haystack | array | Array to search. |
| strict | bool | If 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)