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
Use Array. prototype. splice to get an array of elements excluding this one.
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.
Array.prototype.pop() The pop() method removes the last element from an array and returns that element.
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.
Use array_slice and implode:
$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. If array is empty (or is not an array), NULL will be returned.
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With