我有一个数组:
<?PHP $array = [ 'fruits' => [ 'apple' => 'value','orange' => 'value' ],'vegetables' => [ 'onion' => 'value','carrot' => 'value' ];
我也有一个字符串:
$string = 'fruits[orange]';
有没有办法检查字符串中指定的 – 数组键 – 是否存在于数组中?
例如:
<?PHP if(array_key_exists($string,$array)) { echo 'Orange exists'; }
试试这个.这里我们使用foreach和isset函数.
原文链接:https://www.f2er.com/php/137127.htmlNote: This solution will also work for more deeper levels Ex:
fruits[orange][x][y]
<?PHP ini_set('display_errors',1); $array = [ 'fruits' => [ 'apple' => 'value','orange' => 'value' ],'vegetables' => [ 'onion' => 'value','carrot' => 'value' ] ]; $string = 'fruits[orange]'; $keys=preg_split("/\[|\]/",$string,-1,PREG_SPLIT_NO_EMPTY); echo nestedIsset($array,$keys); function nestedIsset($array,$keys) { foreach($keys as $key) { if(array_key_exists($key,$array))://checking for a key $array=$array[$key]; else: return false;//returning false if any of the key is not set endif; } return true;//returning true as all are set. }