简体   繁体   中英

How to check if there exists a key in an array that contains a certain string in php?

I am working on a webapp right now in PHP. So far there is a defined array with the following structure:

$array = array("check_first" => true, "check_second" => false)

There are also much other arrays with default numerical structure with keys: 0, 1,2,3 etc.

I want now to make a difference between the arrays with keys of numerical and arrays with keys of strings that starts with "check_".

So I would like to search through all my defined arrays if there is a array with keys that contains the string "check_". I would prefer a simple if-statement for this.

I hope this makes sense. Thanks for all your comments!

  • Step 1: loop through the array with foreach
  • Step2 for each entry, check if the key starts with your string using strpos($key, 'check_')!==false

One approach is to get all the array keys, concatenate them into a single string, then use strpos to test if athere are any instances of 'check_'.

if (strpos(implode('',array_keys($arr)),'check_') !== false) {
    echo 'This array has "check_" keys!';
}

Although this is coded concisely it includes three function calls, two of which are applied to all of the array elements. A foreach loop that breaks on the first match may be faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM