Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find unknown array key in php?

Tags:

php

I have an array

$array = array (
  'pubMessages' => 
  array (
    0 => 
    array (
      'msg' => 'Not bad',
      'type' => 'warning',
    ),
    1 => 
    array (
      'msg' => 'Bad',
      'type' => 'error',
    ),
  ),
);

To remove the sub array having 'type' => 'error', I use bellow code

$key = array_search('error', $array);
unset($array["pubMessages"][$key]);

The key name of the array pubMessages is changed every time, please tell me how to get this key name dynamically? The count of arrays in pubMessages is also variable.

like image 584
DMP Avatar asked Mar 04 '23 21:03

DMP


2 Answers

Get dynamic key name using array_keys() and then loop through inner array and check if key type is equal to error remove it.

$dynamicKey = array_keys($array)[0];
foreach($array[$dynamicKey] as $item){
    if ($item['type'] == 'error')
        unset($array[$dynamicKey][$key]);
}

Check result in demo

like image 77
Mohammad Avatar answered Mar 16 '23 15:03

Mohammad


I would use an array_filter() on this kind of search, like so:

$array = array(
            'pubMessages' => array (
                0 => array (
                    'msg' => 'Not bad',
                    'type' => 'warning'
                ),
                1 => array (
                    'msg' => 'Bad',
                    'type' => 'error'
                )
            )
        );

// array_search() will return false. It is not how 
// array_search() works on a multi-dimensional array
// $key = array_search('error',$array);

function findError($a) {
    return ($a['type'] != 'error');
}

// deal with "unknown" first index / key name issue
$idx = array_keys($array)[0];
$array[$idx] = array_filter($array[$idx],"findError");

var_dump($array);
exit;

And the output will be:

array(1) {
    ["pubMessages"]=> array(1) {
        [0]=> array(2) {
             ["msg"]=> string(7) "Not bad"
             ["type"]=> string(7) "warning"
        }
    }
}

Edit: Added a fix for the unknown key / index issue

like image 26
Tigger Avatar answered Mar 16 '23 15:03

Tigger