Home > Article > Backend Development > Basic operations and usage of arrays in PHP
Basic operations and usage of arrays in PHP
1. Overview
Array is a very important data type in PHP. It can be used to store multiple values, and can Access these values via index or key. Arrays have rich operations and usage methods in PHP. This article will introduce in detail the basic operations and usage methods of arrays in PHP.
2. Create arrays
In PHP, you can create arrays in two ways: countable arrays and associative arrays.
// Method 1: Use the array() function
$numbers = array(1, 2, 3, 4, 5);
// Method 2: Use [] (available from PHP 5.4)
$numbers = [1, 2, 3, 4, 5];
// Method 1: Use the array() function
$student = array("name" => "John", "age" => ; 18, "grade" => "A");
// Method 2: Use [] (available starting from PHP 5.4)
$student = ["name" => "John ", "age" => 18, "grade" => "A"];
3. Accessing array elements
You can access elements in the array through indexes or keys.
$numbers = array(1, 2, 3, 4, 5);
echo $numbers[0]; // Output 1
echo $numbers[2 ]; // Output 3
$student = array("name" => "John", "age" => 18, "grade" => "A");
echo $student["name"]; // Output John
echo $student["age"]; // Output 18
4. Common array operations and functions
$numbers = array(1, 2, 3, 4, 5);
echo count($numbers); // Output 5
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $number) {
echo $number . " ";
}
//Output 1 2 3 4 5
$numbers = array(1, 2, 3, 4, 5);
// Use [] to add elements
$numbers[] = 6;
// Use array_push() to add elements
array_push($numbers, 7);
print_r($numbers);
// Output Array (1, 2, 3, 4 , 5, 6, 7)
$numbers = array(1, 2, 3, 4, 5);
unset($numbers[2]);
print_r($numbers );
// Output Array (1, 2, 4, 5)
5. Summary
This article introduces the basic operations and usage of arrays in PHP, including creating arrays and accessing array elements , get the array length, traverse the array, and add and remove elements. Arrays are a very important data type in PHP and are often used in actual development. Mastering the basic operations and usage of arrays can help developers process data more flexibly and efficiently.
The above is the detailed content of Basic operations and usage of arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!