php can add elements to an array without using array functions. In PHP, you can use the array literal "[]" to add elements to and from the end of the array. The syntax is "$array variable name [subscript] = value", where the subscript (index value) can be a string or an integer; note the following Scaling values are not repeatable and therefore cannot be set to an existing value. When a specific index value (subscript) is not specified within square brackets "[]", the default is a numeric index, and the index value will increase sequentially from the original numeric index.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php can be used to add arrays to arrays without using array functions Add elements.
In PHP, we can use the array literal "[]
", in the form of "$array variable name[subscript] = value;
" format adds elements to and from the end of the array.
Subscript
can be a string, an integer, or empty (that is, no specific index value is specified).
<?php header("Content-type:text/html;charset=utf-8"); $array = array('Apple' => '苹果','Banana' => '香蕉','Orange' => '橘子','Plum' => '李子','Strawberry' => '草莓'); var_dump($array); $array[0] = '欢迎'; $array[1] = '来到'; $array[2] = 'PHP中文网'; $array['url'] = 'https://www.php.cn/'; //输出语句 var_dump($array); ?>
Note: The subscript value cannot be repeated. If it is repeated, the element is not added but replaced, so it cannot be set to an existing value.
<?php header("Content-type:text/html;charset=utf-8"); $array= array("香蕉","苹果","梨子","橙子","橘子","榴莲"); var_dump($array); $array[0] = '欢迎'; $array[1] = '来到'; $array[2] = 'PHP中文网'; $array['url'] = 'https://www.php.cn/'; //输出语句 var_dump($array); ?>
If you are worried that the set subscript already exists (replacement element), it becomes a replacement element; you can not specify a specific index value in square brackets, so the default is Numeric index, the index value will increase sequentially from the original numerical index.
<?php header('content-type:text/html;charset=utf-8'); $array= array("香蕉","苹果","梨子","橙子","橘子","榴莲"); var_dump($array); $array[] = '欢迎'; $array[] = '来到'; $array[] = 'PHP中文网'; $array[] = 'https://www.php.cn/'; //输出语句 var_dump($array); ?>
The previous subscript is a string, then the index value starts from 0 and increases sequentially
<?php header("Content-type:text/html;charset=utf-8"); $array = array('Apple' => '苹果','Banana' => '香蕉','Orange' => '橘子','Plum' => '李子','Strawberry' => '草莓'); var_dump($array); $array[] = '欢迎'; $array[] = '来到'; $array[] = 'PHP中文网'; $array[] = 'https://www.php.cn/'; //输出语句 var_dump($array); ?>
Recommended learning : "PHP Video Tutorial"
The above is the detailed content of Can PHP add elements to an array without using array functions?. For more information, please follow other related articles on the PHP Chinese website!