Jump to content

Remove subarray


Jonob

Recommended Posts

I have a multi-dimensional array. Lets assume its something like:

 

[0]
  [0] -> 'Green'
  [1] -> 'Soccer'
  [2] -> 'Oranges'
[1]
  [0] -> 'Blue'
  [1] -> 'Rugby'
  [2] -> 'Apples'

 

I want to remove the [2] index frome each sub-array, so that I land up with:

 

[0]
  [0] -> 'Green'
  [1] -> 'Soccer'
[1]
  [0] -> 'Blue'
  [1] -> 'Rugby'

 

I can do this easily by looping through ...but is there an easier/faster way?

Link to comment
Share on other sites

Yes, there is a much easier method: array_diff_key()

 

Using your example above:

 

//Create an array with idexes of those to be removed
$arrayKeysToRemove = array('2' => '');

$newArray = array_diff_key($originalArray, $arrayKeysToRemove);

 

Link to comment
Share on other sites

array_diff_key wont work like that. You would need to build an array exactly the opposite of what you want then diff it against the original array. ie

array(

array(2=>'')

array(2=>'')

etc for each sub array

 

The fastest and easiest way is the foreach you have been previously shown.

 

 

HTH

Teamatomic

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.