什么是array_slice()? [英] What is array_slice()?

查看:115
本文介绍了什么是array_slice()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP开发的新手:我在PHP网站上查找了一个函数- array_slice 。我阅读并查看了示例,但我不明白。有人可以为我清楚地解释一下吗?

I'm new to PHP development: I looked on the PHP website for a function - array_slice. I read and looked at the example but I don't understand it. Can someone explain this in clear words for me?

我认为它的工作原理如下?

I think it works as follow?

$example = array(1,2,3,4,5,6,7,8,9);
$offset = 2;
$length = 5;
$newArray = array_slice($example, offset, length);

the result of $newArray is: $newArray(3,4,5,6,7);


推荐答案

除了stefgosselin的答案有一些错误:让我们从他的数组开始:

In addition to stefgosselin's answer that has some mistakes: Lets start with his array:

$input = array(1,2,3);

其中包含:

array(3) {
    [0]=> int(1)
    [1]=> int(2)
    [2]=> int(3)
}

然后您 array_slice

var_dump(array_slice($input, 1));

该函数将返回第一个元素之后的值(这就是第二个参数,偏移量的含义) 。但是请注意按键!

The function will return the values after the first element (thats what the second argument, the offset means). But notice the keys!

array(2) {
    [0]=> int(2)
    [1]=> int(3)
}

请记住,直到您将密钥保留下来传递 true 作为第四个 preserve_keys 参数。另外,因为在此之前还有另一个 length 参数,如果要返回偏移量之后的所有内容,则必须传递 NULL

Keep in mind that keys aren't preserved, until you pass true for the fourth preserve_keys parameter. Also because there is another length parameter before this, you have to pass NULL if you want to return everything after the offset, but with the keys preserved.

var_dump(array_slice($input, 1, NULL, true));

这将返回stefgosselin(错误地)最初写的内容。

That will return what stefgosselin (incorrectly) wrote initially.

array(2) {
    [1]=> int(2)
    [2]=> int(3)
}

这篇关于什么是array_slice()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆