简体   繁体   English

如何检查数组中是否包含包含特定字符串的键?

[英]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. 我现在正在使用PHP开发一个webapp。 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. 还有许多其他具有默认数字结构且键为0、1、2、3等的数组。

I want now to make a difference between the arrays with keys of numerical and arrays with keys of strings that starts with "check_". 现在,我想在带有数字键的数组与以“ check_”开头的字符串键的数组之间有所区别。

So I would like to search through all my defined arrays if there is a array with keys that contains the string "check_". 因此,我想搜索所有定义的数组,如果有包含键的数组包含字符串“ check_”。 I would prefer a simple if-statement for this. 我更喜欢一个简单的if语句。

I hope this makes sense. 我希望这是有道理的。 Thanks for all your comments! 谢谢你们的评论!

  • Step 1: loop through the array with foreach 步骤1:使用foreach数组
  • Step2 for each entry, check if the key starts with your string using strpos($key, 'check_')!==false 步骤2对于每个条目,使用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_'. 一种方法是获取所有数组键,将它们连接到单个字符串中,然后使用strpos来测试atcheck是否存在任何实例。

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. 在第一个比赛中中断的foreach循环可能会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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