Home » Php » How to search for a needle in multi-dimensional array in php?

How to search for a needle in multi-dimensional array in php?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have some different type of php arrays which can have sensitive data at any level of nesting. I want to unset this sensitive keys. How should I go about this?

For e.g. sensitive data keys can be account_no, acc_no etc

Sample request array1:

[
    'ClientCode'   => "abcom",
    'MerchantCode' => "Code1",
    'acc_no'       =>  "12345"
]

This array should become

[
    'ClientCode'   =>  "abcom"
    'MerchantCode' =>  "Code1"

]

Sample request array2:

  [
      'customer_name' => "Umesh",
      'age' => 24,
      'customer_details' => [
          'mob_no' => "989729069",
          'account_no' => '1235'
      ]
  ]

This array should become

[
      'customer_name' => "Umesh",
      'age'           => 24,
      'customer_details' => [
          'mob_no' => "989729069"
      ]
]
How to&Answers:

The best solution for any level of nesting is a recursive function:

$your_array = array(
  'client'  => '1234',
  'acc_no'  => '12345',
  'test'    => array(
    'acc_no'  => '12',
    'acc'    => '12345'
  )
);

function unset_sensitive_keys( &$array, $delete_keys )  {
  foreach( $array as $key => &$value ) {
    if( is_array( $value ) )  {
      unset_sensitive_keys( $value, $delete_keys );
    } else {
      if( in_array( $key, $delete_keys )  ) {
        unset($array[$key]);
      }
    }
  }
}

unset_sensitive_keys( $your_array, array( 'acc_no', 'account_no' ) );

Answer:

Solution without loop

In the first array:

unset($arr['acc_no']);

In the second array:

unset($arr['customer_details']['account_no']);

Solution using loops

First array:

foreach($arr1 as $key => $value) {
   if($key === 'acc_no') {
      unset($arr1['acc_no']);
   }
}

Second array:

foreach($arr2 as $key => $value) {
    if($key === 'customer_details') {
        unset($arr2['customer_details']['account_no']);
    }
}