PHP - check if one or more array fields exist

I have an array like this:

array('prefix1_field' => 34,
      'prefix1_anotherfield' => 345,
      'prefix1_andanotherfield' => 565,

      'anotherprefix_field' => 34,
      'anotherprefix_anotherfield' => 345,
      'anotherprefix_andanotherfield' => 565,

      'prefix3_anotherprefix_field' => 34, // <- 'anotherprefix' here should be ignored
      'prefix3_anotherfield' => 345,
      'prefix3_andanotherfield' => 565,
      ...
);

How can I create a function that checks if there are any fields in this array starting with prefix1_for example?

+3
source share
5 answers
function check_array_key_prefix_exists($array, $key_prefix) {
  $keys = array_keys($array);
  foreach ($keys as $key) {
    if (0 == substr_compare($key, $key_prefix, 0, strlen($key_prefix))) {
      return true;
    }
  }

  return false;
}
+2
source

Sort of:

function check($arr,$prefix) {
        foreach($arr as $key => $value) {
                if(strcmp(substr($key,0,strlen($prefix)),$prefix)==0) {
                        return true;
                }
        }
        return false;
}
+2
source

?

function array_has_key_prefix( $array, $key_prefix ) {
  foreach($arr as $key => $value) {
    if( preg_match( "/^" . $key_prefix . "/", $key ) )
      return true;
  }
  return false;
}
+2

:

$data=array('prefix1'=>array(
                  'field'=>34,
                  'anotherfield'=>345,
               ),
            'prefix2'=>array(
                  'field'=>56,
               ),

... ...

PHP array_key_exists().

, , array_key_exists(), foreach() explode(), .

+1

, s.t. .

function check_array_key_prefix_exists($array, $key_prefix) {
  $keys = array_keys($array);
  foreach ($keys as $key) {
    if (preg_match("#^$key_prefix", $array) {
      return true;
    }
  }

  return false;
}

I do not know if I answered your question because I did not run it into it. Good luck

+1
source

Source: https://habr.com/ru/post/1763975/


All Articles