delete specific elements from an associative array

I am working with two arrays:

$pool = array(
     'foo' => array('foobar1'),
     'bar' => array('foobar2'),
     'lou' => array('foobar3'),
     'zuu' => array('foobar4') 
);

$remove = array('lou', 'zuu');

What is the best way to create this new array:

$result = array(
     'foo' => array('foobar1'),
     'bar' => array('foobar2')
);

Instead of using a foreach loop, I prefer a more concise solution like:

$result = array_intersect_key( $pool, array_flip($remove) );

This code snippet gives me the opposite result:

array(
     'lou' => array('foobar3'),
     'zuu' => array('foobar4')
);

UPDATE: Here is my single line solution:

array_intersect_key( $pool, array_flip( array_keys( array_diff_key( $pool, array_flip( $remove ) ) ) ) )

Answer №1

give this a shot

$collection = array(
     'apple' => array('red'),
     'banana' => array('yellow'),
     'grape' => array('purple'),
     'kiwi' => array('green')
);

$remove_fruit = array('banana', 'grape');
$filtered_collection = array_diff_key($collection, array_flip($remove_fruit));
var_dump(array_intersect_key($collection, $filtered_collection));

Answer №2

To remove an element from an array, you can utilize the unset function.

unset($items['apple']);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create an htaccess file for showing user-friendly URLs?

I have recently created a website and I am trying to set up a user-friendly URL structure. Currently, the URL for my website looks like this: http://example.com/1/post To achieve this, I am passing query strings in the following way: <a href="page.ph ...

Numerous variables leading to unique strings

When extracting variables from a URL, I create a string that varies based on whether the variable exists in the URL or not. Here's an illustration: Consider these two URLs: www.domain.com/list.php?cli=paris&resp=James&type=emp www.domain.co ...

Issue occurred when attempting to send the STMT_PREPARE packet, with the Process ID being

I can't seem to figure out why this bug keeps happening. Here is the script I am using: foreach($brands as $brand){ // about 600items for this loop .... .... DB::table('mailing_list')->insert(array( &ap ...

Guide on calculating the quantity of rows in a Json data set

How can I determine the number of rows where my ID is present in one of the fields, which are stored as JSON objects: { "Monday":{"1":"15","2":"27","3":"74","4":"47","5":"42","6":"53"}, "Tuesday":{"1":"11","2":"28","3":"68","4":"48","5":"43","6":"82"} ...

Nginx's sluggish SSL downloads at a snail's pace

I have configured this virtual host: server { server_name admin.ex.com ; listen 80 ; listen [::]:80 ; ##SSL #listen 443 ssl ; listen *:443 ssl http2 ; listen [::]:443 ssl http2 ; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #s ...

Loop within PHP code that executes specific operations, such as a matching engine for orders

I am currently working on creating a simulated asset exchange platform using PHP. Let's consider the orderbook for a specific asset, XYZ: | buy_price | amount | sell_price | amount | |-----------|--------|------------|--------| | 99.3 | 100 | ...

Discover the optimal method of incorporating the router within CodeIgniter helper by leveraging the CI instance, for instance, employing $CI->router->fetch_method()

I am attempting to create a new method within a custom helper, but unfortunately, the code is not functioning as expected. The issue lies in being unable to access the router through the CI instance. if ( ! function_exists('active_link')) { ...

How can I fetch data from SQL using JavaScript based on a specific value in PHP?

My application is built using the Yii2 framework. Within my application, there is a view.php file that consists of an element and a button. The element, <div id="userId">, contains the user's login ID, and I aim to use the button to re ...

In JavaScript, combine two arrays of equal length to create a new array object value

Trying to figure out how to merge two arrays into a new object in JavaScript var array1 = ['apple', 'banana', 'orange']; var array2 = ['red', 'yellow', 'orange']; If array1[0] is 'apple&apos ...

Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness? <div id="accordion" class="display-data"> ...

Divide PHP array by its key

I have an array with ordered but non-consecutive numerical keys: Array ( [4] => 2 [5] => 3 [6] => 1 [7] => 2 [8] => 1 [9] => 1 [10] => 1 ) My goal is to split this array into two separate arrays. One shoul ...

Unable to modify the selector to "Remove preview files" on click in PHP and JavaScript

During the process of uploading multiple files (using <input type="file" multiple/>) with preview image file and successfully removing the image preview and file data, I encountered a problem. The issue arises when attempting to change the selector ...

PHP Ajax search fails to load live results

While working on my project to create an ajax live search feature, I encountered an error stating 'undefined index = q'. Below is the jQuery code I used: <script> $(document).ready(function(e){ $("#search").keyup(function(){ ...

Retrieving Data from Database Using Laravel and Ajax Post-Update

I am facing an issue with my edit form, designed for admins to edit book details. Upon submitting the form, the values are updated in the database successfully. However, the page fails to load the updated values into the form without requiring a refresh/re ...

Retrieve the GET parameters from a URL string

Is there a simple way to extract GET variables passed through a URL in PHP? The URL is not for the actual page itself. For example, if I have a string like: What is the most effective method to retrieve the values of those variables? ...

Can a page be replaced by another include?

THE ISSUE I am facing a problem where I am unable to override the current page using include. if ($LS::getUser('clan') || isset($_GET['clan']) && !isset($_GET['search'])) { include("res/templates/clan-overview.ph ...

What is the best way to determine the size of the URLs for images stored in an array using JavaScript?

I am working on a project where I need to surround an image with a specific sized 'div' based on the image's dimensions. The images that will be used are stored in an array and I need to extract the height and width of each image before disp ...

Converting JSON object to an array or list using deserialization

I'm not sure what to ask, so I apologize if this is poorly thought out. The other questions I have found are about people receiving object arrays in JSON. Instead of an array, my JSON string is returning as an object. This is new for me because I hav ...

Implementing array values into a jQuery graph syntax

After json encoding from php, I have an array that contains information on different categories: [{"Type":"Category","Name":"games","TotalClicks":"162"},{"Type":"Category","Name":"apps","TotalClicks":"29"},{"Type":"Category","Name":"music","TotalClicks":" ...

How can you divide a single PDF file into multiple pages with the Laravel framework?

I'm currently engaged in a project that requires a PDF splitting feature for a website. Does anyone know how to divide a PDF file into individual pages? I've attempted using www.splitapdf.com for splitting my PDF into separate pages, but now I n ...