1

I have this array :

Array ( [0] => Array ( [nid] => 1 [language] => EN [uid] => 1 [tid] => page [title] => Welcome [body] => Comming Soon. [date_post] => 2014-02-18 08:27:56 [enable] => 1 ) [1] => Array ( [nid] => 2 [language] => EN [uid] => 1 [tid] => page [title] => Our Stuff [body] => Comming Soon. [date_post] => 2014-02-18 08:27:56 [enable] => 1 ) [2] => Array ( [nid] => 3 [language] => EN [uid] => 1 [tid] => page [title] => Partners [body] => Comming Soon. [date_post] => 2014-02-18 08:27:56 [enable] => 1 ) 

And so on... What i would like to do i unset the element how has the title Partners for example, so I tried this :

unset($pages[array_search('Partners',$pages)]); 

But it remove the first element from the table, so how can i unset the specific element ?

Thanks

2 Answers 2

4

array_search() only searches elements in the main array. Those elements are themselves arrays, so it returns false. You need to to iterate through each sub array either with an array function or a loop:

foreach($array as $key => $value) { if($value['title'] == 'Partners') { unset($array[$key]); } } 
Sign up to request clarification or add additional context in comments.

3 Comments

This answer would be more helpful if it explained what was doing and why the example doesn't work and this does.
@SteveBuzonas: Was headed out, added.
@steffen: Sorry, rushed example, deleted.
4

It's because array_search searches your array for the string 'Partners'. But as your array only contains 3 arrays, no entry is found. array_search will result false which evaluates to 0. That's why the first key is removed.

You need to search inside each array (foreach ($myarray as $array) { ... }). And you also must check the return value:

$value = array_search(...); if ($value !== false) { // do unset } 

Solution with array_filter:

// Remove all arrays having 'title' => 'Partners' $arr = array_filter($arr, function($e) { return $e['title'] != 'Partners'; }); // Remove all arrays containing a value 'Partners' $arr = array_filter($arr, function($e) { return array_search('Partners', $e) === false; }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.