数组函数
7 methods用于操作 PHP 多功能数组类型的面向过程的数组函数。
strlen(string $string): int将一个或多个元素推入 array 的末尾。返回新的元素数量。
Parameters
| Name | Type | Description |
|---|---|---|
| array | string | 输入数组(按引用传递)。 |
Returns
int
Example
php
<?php
echo strlen("hello"); // 5
echo strlen("日本語"); // 9 (UTF-8 bytes)strpos(string $haystack, string $needle, int $offset = 0): int|false弹出并返回数组的最后一个值,将其缩短一个元素。
Parameters
| Name | Type | Description |
|---|---|---|
| array | string | 输入数组(按引用传递)。 |
| needle | string | Substring to find. |
| offset | int | Search starting offset (default 0). |
Returns
int|false
Example
php
<?php
$pos = strpos("Hello, World", "World");
if ($pos !== false) {
echo $pos; // 7
}substr(string $string, int $offset, ?int $length = null): string计算数组或 Countable 对象中所有元素的数量。
Parameters
| Name | Type | Description |
|---|---|---|
| value | string | 数组或 Countable 对象。 |
| mode | int | COUNT_RECURSIVE 用于计算多维数组。 |
| length | ?int | Maximum length (null = to end). |
Returns
string
Example
php
<?php
echo substr("Hello, World", 7); // "World"
echo substr("Hello, World", 7, 3); // "Wor"
echo substr("Hello", -3); // "llo"str_replace(array|string $search, array|string $replace, string|array $subject): string|array将回调函数应用于给定数组的元素并返回一个新数组。
Parameters
| Name | Type | Description |
|---|---|---|
| callback | array|string | 要应用的函数(null = 值数组)。 |
| array | array|string | 输入数组。 |
| subject | string|array | String/array being searched. |
Returns
string|array
Example
php
<?php
echo str_replace("world", "PHP", "hello world"); // "hello PHP"
echo str_replace(["a", "b"], "x", "abc"); // "xxc"strtolower(string $string): string使用回调函数过滤数组元素。不带回调函数时,移除假值。
Parameters
| Name | Type | Description |
|---|---|---|
| array | string | 输入数组。 |
Returns
string
Example
php
<?php
echo strtolower("HELLO World"); // "hello world"explode(string $separator, string $string, int $limit = PHP_INT_MAX): array将一个或多个数组的元素合并在一起。重新索引数字键。
Parameters
| Name | Type | Description |
|---|---|---|
| arrays | string | 要合并的数组。 |
| string | string | Input string. |
| limit | int | Maximum number of elements. |
Returns
array
Example
php
<?php
$parts = explode(",", "a,b,c");
// ["a", "b", "c"]
$parts2 = explode(",", "a,b,c", 2);
// ["a", "b,c"]trim(string $string, string $characters = " \n\r\t\v\x00"): string检查数组中是否存在某个值。使用 strict=true 进行类型安全比较。
Parameters
| Name | Type | Description |
|---|---|---|
| needle | string | 要搜索的值。 |
| haystack | string | 要搜索的数组。 |
Returns
string
Example
php
<?php
echo trim(" hello "); // "hello"
echo trim("---hi---", "-"); // "hi"