Home >Backend Development >PHP Tutorial >Use PHP arrays to implement common scenarios
Use PHP arrays to implement common scenarios
PHP is a popular open source programming language that is widely used in the development of web applications and websites. One of the important features is array (Array), through which large amounts of data can be stored and manipulated. This article will introduce how to use PHP arrays to implement common scenarios, including array creation, traversal, and manipulation.
// 使用 array() 函数创建数组 $fruits = array('apple', 'banana', 'orange'); // 使用方括号 [] 手动声明数组 $numbers = [1, 2, 3, 4, 5];
The keys and values of the array can be of any type, including strings, numbers, Boolean values, objects, etc.
a. Use for loop
Use for loop to traverse numeric index array, for example:
$fruits = array('apple', 'banana', 'orange'); for ($i = 0; $i < count($fruits); $i++) { echo $fruits[$i] . '<br>'; }
b. Use foreach loop
Use foreach loop to traverse associative array and numeric index array, for example:
$person = array('name' => '张三', 'age' => 18); foreach ($person as $key => $value) { echo $key . ': ' . $value . '<br>'; }
c. Use while loop and each() function
Use while loop and each() function to traverse associative array, for example:
$person = array('name' => '张三', 'age' => 18); reset($person); while (list($key, $value) = each($person)) { echo $key . ': ' . $value . '<br>'; }
a. Add elements
Use array_push(), array_unshift(), array_splice() and [] operators to add elements to the array, for example:
$fruits = array('apple', 'banana', 'orange'); array_push($fruits, 'strawberry'); array_unshift($fruits, 'peach'); array_splice($fruits, 2, 0, 'grape'); $fruits[] = 'kiwi';
b . Delete elements
Use unset(), array_pop(), array_shift() and array_splice() to delete elements in the array, for example:
$fruits = array('apple', 'banana', 'orange', 'grape', 'kiwi'); unset($fruits[1]); array_pop($fruits); array_shift($fruits); array_splice($fruits, 1, 2);
c. Modify elements
Use the [] operator and array_splice() can modify the elements in the array, for example:
$fruits = array('apple', 'banana', 'orange', 'grape', 'kiwi'); $fruits[1] = 'pear'; array_splice($fruits, 3, 1, 'mango');
d. Find elements
Use in_array(), array_search(), array_keys() and array_values() to find elements in the array, For example:
$fruits = array('apple', 'banana', 'orange', 'grape', 'kiwi'); if (in_array('orange', $fruits)) { echo '找到了橙子!'; } $key = array_search('apple', $fruits); echo '苹果的索引是:' . $key; $keys = array_keys($fruits); $values = array_values($fruits);
In summary, this article introduces how to use PHP arrays to implement common scenarios, including the creation, traversal and operation of arrays. Mastering these basic skills will make you more comfortable in PHP development.
The above is the detailed content of Use PHP arrays to implement common scenarios. For more information, please follow other related articles on the PHP Chinese website!