How to add elements in php

藏色散人
Release: 2023-03-14 08:12:01
Original
2141 people have browsed it

How to add elements in php: 1. Add array elements through assignment; 2. Add array elements through array_push function; 3. Add elements through array_unshift function; 4. Add elements through array_pad function.

How to add elements in php

The operating environment of this article: windows7 system, PHP7.4 version, DELL G3 computer

How to add elements to php?

1. How to add array elements in php:

(1) Add array elements by assignment: $states['name']='Tom';

(2)int array_push(array target_array,mixed variable [,mixed variable...]) The function adds the variable to the end of the target_array and returns true when successful, otherwise it returns false, where the variable can be multiple;

(3)int array_unshift(array target_array,mixed variable [,mixed variable...]) The function adds variable to the array head of target_array and returns true when successful, otherwise it returns false, where the variable can be multiple. All existing numerical keys will be modified accordingly, while associated keys will not be affected;

(4)array array_pad(array target_array,integer length,mixed pad_value) Increase the size of target_array to the length specified by length.

Specific method:

1. Use the array_merge method to implement a function similar to array_unshift that adds elements at the beginning

The code is as follows:

<?php
$queue = array(&#39;a&#39;, &#39;B&#39;);
$queue = array_merge(array(&#39;front&#39; => &#39;hello&#39;), $queue);
/*
Array
(
[front] => hello
[0] => a
[1] => b
)
*/
?>
Copy after login

2. Operator

The code is as follows:

<?php
$queue = array(&#39;a&#39;, &#39;B&#39;);
$queue = array(&#39;front&#39; => &#39;Hello&#39;) + $queue;
?>
Copy after login

The output result is the same as using the array_merge method.

3. Add an associative array element at the end of the element

The code is as follows:

<?php
$queue = array(&#39;a&#39;, &#39;B&#39;);
$queue[&#39;front&#39;] = &#39;hello&#39;;
/*
输出
Array
(
[0] => a
[1] => b
[front] => hello
)
*/
?>
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to add elements in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!