Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - check if one or more array field exist

Tags:

arrays

php

I have a 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 make a function that checks if there are any fields in this array that start with prefix1_ for example?

like image 962
Alex Avatar asked May 20 '26 06:05

Alex


1 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;
}
like image 82
Dominic Rodger Avatar answered May 24 '26 15:05

Dominic Rodger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!