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.
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.
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 .
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].
Like this!
end($array); $key = key($array); reset($array);
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