简体   繁体   English

获取数组中除最后一个以外的所有值

[英]getting all the values in an array except the last one

I have this right now:我现在有这个:

$s = preg_split('/\s+/', $q);
    $k = end($s);

What I want now is to get all the values in the array $k[] except the last one, and join them in a new string.我现在想要的是获取数组$k[]中除最后一个之外的所有值,并将它们加入一个新字符串中。 So basically if the array was:所以基本上如果数组是:

0 => Hello
1 => World
2 => text

I would get Hello World我会得到Hello World

Use array_slice and implode :使用array_sliceimplode

$k = array( "Hello", "World", "text" );
$sliced = array_slice($k, 0, -1); // array ( "Hello", "World" )
$string = implode(" ", $sliced);  // "Hello World";

If you can modify the array:如果可以修改数组:

array_pop($k);
$string = join(' ', $k);

array_pop() pops and returns the last value of the array, shortening the array by one element. array_pop() 弹出并返回数组的最后一个值,将数组缩短一个元素。 If array is empty (or is not an array), NULL will be returned.如果数组为空(或不是数组),则返回 NULL。

Source资源

Use array_slice($array) to get a subset of any array.使用array_slice($array)获取任何数组的子集。

For everything without the last item I believe it is对于没有最后一项的一切,我相信它是

$return = array_slice($array, 0, count($array)-1, true);

Testcase http://codepad.org/fyHHX5Us测试用例http://codepad.org/fyHHX5Us

Something like this:像这样的东西:

<?php

    $array = array('Hello', 'World', 'text');
    $new_array = array_slice($array,0,-1);
    echo implode(' ',$new_array);

?>

Example例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM