I have a PHP array like so:
$messages = [312, 401, 1599, 3, ...];
Given that the values in the array are unique, how can I delete the element with a given value (without knowing its key)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using
array_search()andunset, try the following:array_search()returns the key of the element it finds, which can be used to remove that element from the original array usingunset(). It will returnFALSEon failure, however it can return a false-y value on success (your key may be0for example), which is why the strict comparison!==operator is used.The
if()statement will check whetherarray_search()returned a value, and will only perform an action if it did.