Home  >  Article  >  Backend Development  >  Detailed explanation and example demonstration of PHP array functions

Detailed explanation and example demonstration of PHP array functions

WBOY
WBOYOriginal
2024-03-13 17:54:031470browse

Detailed explanation and example demonstration of PHP array functions

Detailed explanation and example demonstration of PHP array function

In PHP development, array is a very important data structure, which can store multiple values ​​​​and pass keys These values ​​are accessed as value pairs. PHP provides many powerful array functions that can help us perform various operations on arrays. This article will introduce the commonly used array functions in PHP in detail and give actual code examples to demonstrate their usage.

1. array_merge()

array_merge()The function is used to merge one or more arrays into one array. The merged array will contain all elements in the input arrays, and the keys will be re-indexed.

$array1 = array('red', 'green');
$array2 = array('blue', 'yellow');
$mergedArray = array_merge($array1, $array2);

print_r($mergedArray);

The output result is:

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => yellow
)

2. array_push()

array_push()The function adds one or more elements to the end of the array.

$fruits = array('apple', 'banana');
array_push($fruits, 'orange', 'grape');

print_r($fruits);

The output result is:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

3. array_pop()

array_pop() function is used to delete the last element of the array.

$numbers = array(1, 2, 3, 4);
$lastNumber = array_pop($numbers);

print_r($numbers);
echo $lastNumber;

The output result is:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
4

### 4. array_keys()

`array_keys()`函数返回数组中所有的键名。

$student = array('name' => 'Alice', 'age' => 20, 'grade' => 'A' );
$keys = array_keys($student);

print_r($keys);

输出结果为:

Array
(

[0] => name
[1] => age
[2] => grade

)

### 5. array_values()

`array_values()`函数返回数组中所有的值。

$student = array('name' => 'Alice', 'age' => 20, 'grade' => 'A');
$values ​​= array_values($student);

print_r($values);

输出结果为:

Array
(

[0] => Alice
[1] => 20
[2] => A

)

The above is the detailed content of Detailed explanation and example demonstration of PHP array functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn