PHP数组键存在于string中

前端之家收集整理的这篇文章主要介绍了PHP数组键存在于string中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个数组:
<?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函数.

Note: This solution will also work for more deeper levels Ex: fruits[orange][x][y]

Try this code snippet here

<?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.
}
原文链接:https://www.f2er.com/php/137127.html

猜你在找的PHP相关文章