re1man
re1man

Reputation: 2367

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. So basically if the array was :

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

I would get Hello World

Upvotes: 27

Views: 29235

Answers (4)

Josh
Josh

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

Paul DelRe
Paul DelRe

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.

Source

Upvotes: 8

Madara's Ghost
Madara's Ghost

Reputation: 174977

Something like this:

<?php

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

?>

Example

Upvotes: 1

sg3s
sg3s

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

Related Questions