phparrayswordpressmultidimensional-array

Determine if a column name exists in a 2d array


I have a little problem coding if statement in wordpress. My plugin stores custom registration fields in one single row in database, lets say "custom_fields". When I print custom_fields using get_user_meta I got an array of all information stored there, eg:

Array (
  [0] => Array (
    [invoice_company_name] => x
    [invoice_nip] => x
    [invoice_street] => x
    [invoice_street_number] => x
    [invoice_post_code] => x
    [invoice_city] => x
    [invoice_country] => x
    [birth_date] => x
    [birth_city] => x
    [district] => x
  )
)

I want to check if all fields starting with invoice exists. Of course where are the 'x' there are real values.

Well I found function in_array(), so tried to do something like this, but it doesn't work

$user_ID = get_current_user_id();
$all_meta_for_user = get_user_meta(
    $user_ID,
    'wp_s2member_custom_fields', false
);
print_r($all_meta_for_user);
if (in_array("[invoice_company_name]", $all_meta_for_user)) {
    echo "exist";
} else {
    echo 'dont exist';
}

And I got 'dont exist' :) What's going wrong? Also, can I check all the values at once? Something like in_array([1st]&&[2nd]&&[3rd])?

Thanks!


Solution

  • If your array is multi-dimensional, you could search by key using array_key_exists() :

    foreach($all_meta_for_user as $key=>$val){
      if (array_key_exists('invoice_company_name', $val)) 
        {
          echo "exist in key ".$key;
        } 
      else 
        {
          echo "does not exist in key ".$key;
        }
    }
    

    Demo