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
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]);
}
}
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; });