Skip to content
Fix Code Error

PHP array delete by value (not key)

March 13, 2021 by Code Error
Posted By: Anonymous

I have a PHP array as follows:

$messages = [312, 401, 1599, 3, ...];

I want to delete the element containing the value $del_val (for example, $del_val=401), but I don’t know its key. This might help: each value can only be there once.

I’m looking for the simplest function to perform this task, please.

Solution

Using array_search() and unset, try the following:

if (($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

Answered By: Anonymous

Related Articles

  • Reset/remove CSS styles for element only
  • Aurelia - help understanding some binding behavior…
  • Unset WooCommerce checkout fields based on cart…
  • Reference — What does this symbol mean in PHP?
  • CSS Variable trough Polymer (dynamically loaded) elements
  • Aurelia issue with setting element class based on…
  • vuejs Data property undefined
  • How does PHP 'foreach' actually work?
  • Deleting an element from an array in PHP
  • Why am I getting a "401 Unauthorized" error in Maven?
  • Aurelia, long list of bindables on custom element. Refactor?
  • Htaccess: add/remove trailing slash from URL
  • SVG Mask is "bleeding" on canvas edges
  • Edit item description in array in Vue JS
  • firebase storage java.lang.IllegalStateException:…
  • How would I run an async Task method synchronously?
  • How to make an async Task continue with next task…
  • Lists and Components not updating after data change…
  • PHP parse/syntax errors; and how to solve them
  • Laravel 5: Updating Multiple Records
  • Backbone.js DOM isn't ready in render method to…
  • What's better at freeing memory with PHP: unset() or…
  • Do you have to put Task.Run in a method to make it async?
  • PHP Remove elements from associative array
  • Task.Run with Parameter(s)?
  • Smart way to truncate long strings
  • PHP: How to remove specific element from an array?
  • What's the best way to get the last element of an…
  • How to persist state of Svelte components in a virtual list?
  • Ember - Error while processing route: task.edit…
  • Vue JS - How to do conditional display of text based…
  • Python, tkinter: Can't save with Pickle
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • What is your most productive shortcut with Vim?
  • Object Value Returning 'Undefined' in Array in vue.js
  • Asynchronously wait for Task to complete with timeout
  • VueJs: Focus on Input using v-el Directive inside…
  • SignInManager.SignInAsync doesn't sign me in (Vue.js SPA)
  • How to filter a RecyclerView with a SearchView
  • Invert boolean on click with v-for?
  • While updating the variable with index, all the…
  • VueJS: `v-for` not rendering elements
  • Adding classes to a parent div on click
  • Python: Sorting based on class attribute
  • Sample task application with drag and drop
  • Reference - What does this regex mean?
  • Synchronously waiting for an async operation, and…
  • Error: 0xC0202009 at Data Flow Task, OLE DB…
  • async await return Task
  • Running parallel async tasks and return result in…
  • data.table vs dplyr: can one do something well the…
  • How to prevent scrolling the whole page?
  • How do the PHP equality (== double equals) and…
  • Cannot implicitly convert type 'string' to…
  • getting error while updating Composer
  • For-each over an array in JavaScript
  • Polymer.dart How to query for nodes inside the…
  • How to make vuetify v-data-table vertically span all…
  • Using SASS with Aurelia's Skeleton Navigation project
  • How do I return the response from an asynchronous call?
  • Laravel + Vue.js. Load more data when i click on the button
  • Backbone: remove ellipsis onclick
  • Vue.js unknown custom element
  • Is it possible to apply CSS to half of a character?
  • NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack
  • How to show data automatically without refresh with…
  • What are the undocumented features and limitations…
  • Issue adding access token to header in Backbone: It…
  • Filter the query result only and not the entire table
  • How to create a temporary table in SSIS control flow…
  • Backbone Sorting and Updating a listview after an action
  • Running multiple async tasks and waiting for them…
  • Execute a PHP script from another PHP script
  • What's the difference between eval, exec, and compile?
  • Use ForEach to make Unique Sheets on Button Press in…
  • Automating access token refreshing via interceptors in axios
  • When correctly use Task.Run and when just async-await
  • "Notice: Undefined variable", "Notice: Undefined…
  • Getting index of a data in an array in VUE js
  • If my interface must return Task what is the best…
  • How do you parse and process HTML/XML in PHP?
  • How do I wait until Task is finished in C#?
  • Backbone js - Uncaught type error: Cannot read…
  • How do I count unique visitors to my site?
  • Get the index of a certain value in an array in PHP
  • load and execute order of scripts
  • Git - Pushing code to two remotes
  • Avoid creating new session on each axios request laravel
  • How to cancel a Task in await?
  • javascript .replace and .trim not working in vuejs
  • How to create websockets server in PHP
  • Callback functions in C++
  • Cannot access a disposed object. Object name:…
  • Model.set() with new and undefined values in Backbone.js
  • Completely remove attribute from Backbone.js model
  • How to call different Flutter functions based on…
  • await vs Task.Wait - Deadlock?
  • How to remove specific element from array in php
  • Most efficient method to groupby on an array of objects
  • Axios Interceptors retry original request and access…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Remove leading or trailing spaces in an entire column of data

Next Post:

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error