Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify the last element in an array

Tags:

How do I modify the last element in an array?

The array looks like this:

$fields = array("firstName = 'Bob', ",                 "lastName = 'Smith', ",                 "email = '[email protected]', ",                 "address = '123 anystreet', "); 

The array is generated by a script which creates the values and adds the comma/space at the end of each string. I want to remove that comma/space from only the last element in that array. Keep in mind that the values could in fact contain a comma/space combination so only the last element and the last two characters of the last element need to be removed.

I've looked at the end() function but I don't think that is going to help since it just gets the value.

Edit Ok so I created this function/array so that I would only have one mysql function to update users. Sort of like a detect changes function and it only passes back the required/changed fields. I didn't realize there were problems associated with this approach. I thought that since I already had the mysql queries written in my old functions there shouldn't be an issue with this way. The file that it's in will not be accessible to the public. I'm going to use the best answer that works for me but I'm going to search for why this is problematic and I would appreciate comments/links as to what is wrong with this approach. Thanks.

like image 950
John the Ripper Avatar asked Dec 31 '12 18:12

John the Ripper


People also ask

How do I change the last element in an array?

To remove the last element from an array, call the pop() method on the array, e.g. arr. pop() . The pop method removes the last element from the array and returns it. The method mutates the original array, changing its length.

How can I change the last element of an array in PHP?

Answer: Use the PHP array_pop() function You can use the PHP array_pop() function to remove an element or value from the end of an array. The array_pop() function also returns the last value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL .

What is the last element in an array?

The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].


1 Answers

Like this!

end($array); $key = key($array); reset($array); 
like image 199
David Harris Avatar answered Sep 17 '22 15:09

David Harris