Detailed explanation and example demonstration of PHP array functions

WBOY
Release: 2024-03-13 17:56:01
Original
1469 people have browsed it

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);
Copy after login

The output result is:

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

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);
Copy after login

The output result is:

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

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;
Copy after login

The output result is:

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

### 4. array_keys()

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

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

print_r($keys);

输出结果为:
Copy after login
Copy after login

Array
(

[0] => name
[1] => age
[2] => grade
Copy after login

)

### 5. array_values()

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

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

print_r($values);

输出结果为:
Copy after login
Copy after login

Array
(

[0] => Alice
[1] => 20
[2] => A
Copy after login

)

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template