Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting all the values in an array except the last one

Tags:

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

like image 922
re1man Avatar asked Aug 17 '11 16:08

re1man


People also ask

How do you select all other values in an array except the ith element?

Use Array​. prototype​. splice to get an array of elements excluding this one.

How do you exclude values in an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

Which function remove the last item from the array?

Array.prototype.pop() The pop() method removes the last element from an array and returns that element.

How do I find the first and last elements of an array?

The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index. The array length property in JavaScript is used to set or return the number of elements in an array.


2 Answers

Use array_slice and implode:

$k = array( "Hello", "World", "text" ); $sliced = array_slice($k, 0, -1); // array ( "Hello", "World" ) $string = implode(" ", $sliced);  // "Hello World"; 
like image 143
Josh Avatar answered Sep 27 '22 21:09

Josh


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

like image 37
Paul DelRe Avatar answered Sep 27 '22 21:09

Paul DelRe