In PHP, there are two conventional array assignment methods:
1. Use the "array()" function to create an array
In PHP, create an empty array or an array with For arrays of elements, we often use the array() function. The syntax is as follows:
$array_var_name = array();
Alternatively, we can add elements directly within the array function, the syntax is as follows:
$array_var_name = array('元素1', '元素2', '元素3');
Note: When using the array() function to declare an array, if within the square brackets "[ ]" omit the array subscript, the PHP engine will automatically assign consecutive integer subscripts starting from 0 to the array elements. The sample code is as follows:
$array = array('Apple', 'Orange', 'Banana'); // 等价于 $array[0] = 'Apple'; $array[1] = 'Orange'; $array[2] = 'Banana';
2. Use the "[]" operator to assign array elements
In addition to using the array() function, PHP also provides the "[]" operator, which can be used Add new elements to the array. The sample code is as follows:
$array_var_name = []; // 空数组 $array_var_name[] = '元素1'; $array_var_name[] = '元素2'; $array_var_name[] = '元素3';
is equivalent to
$array_var_name = array(); $array_var_name[] = '元素1'; $array_var_name[] = '元素2'; $array_var_name[] = '元素3';
Note: When using the "[]" method to add new elements to the array, PHP will automatically add elements to the next consecutive position in the array. The premise is that the subscript of the new element is not specified! If a subscript is specified, it is added to the specified position. The sample code is as follows:
$a = array('a', 'b', 'c'); $a[8] = 'z'; // 或者 $a['key'] ='z'; var_dump($a); //输出 //array(4) { // [0]=> // string(1) "a" // [1]=> // string(1) "b" // [2]=> // string(1) "c" // [8]=> // string(1) "z" //}
In addition to these two methods, PHP also provides many array-related operation functions and methods, such as "array_pop()", "array_push()", "array_shift()", " array_unshift()" and so on. Mastering these functions can make your PHP development more efficient and convenient!
The above is the detailed content of What are the two ways to assign values to php arrays?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor
