php赋值元素到数组头部(array_unshift的用法)

WBOY
Release: 2016-06-20 13:05:14
Original
1033 people have browsed it

在php中像数组中添加元素比较常见的是array_push函数,即数组的入栈操作,但是这个函数是将元素添加到数组的末尾,如果需要将数组元素压入到数组的头部(即第一个元素)该如何操作呢?

使用php内置函数 array_unshift ,下面就将 array_unshift 这个函数的用法列举一下。

array_unshift该函数的作用是在数组开头插入一个或多个元素。被加上的元素作为一个整体添加,这些添加的元素在数组中的顺序和在参数中的顺序一样。修改后的数组中所有的数值键名将修改为从零开始重新计数,所有的文字键名保持不变。

该函数会返回操作后数组中元素的个数。

语法:

int array_unshift ( array &$array ,mixed $var [,mixed $... ] )
Copy after login

例如:

<p><?php</p>$queue = array("phpernote",".com");<br />array_unshift($queue,"apple","raspberry");<br /><p>print_r($queue);
Copy after login

以上例程会输出:

Array

(
    [0] => apple
    [1] => raspberry
    [2] => phpernote
    [3] => .com
)


Related labels:
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!