Reputation: 2367
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. So basically if the array was :
0 => Hello
1 => World
2 => text
I would get Hello World
Upvotes: 27
Views: 29235
Reputation: 8191
Use array_slice and implode:
$k = array( "Hello", "World", "text" );
$sliced = array_slice($k, 0, -1); // array ( "Hello", "World" )
$string = implode(" ", $sliced); // "Hello World";
Upvotes: 61
Reputation: 4039
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. If array is empty (or is not an array), NULL will be returned.
Upvotes: 8
Reputation: 174977
Something like this:
<?php
$array = array('Hello', 'World', 'text');
$new_array = array_slice($array,0,-1);
echo implode(' ',$new_array);
?>
Upvotes: 1
Reputation: 9567
Use array_slice($array)
to get a subset of any 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
Upvotes: 2