加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP数组键存在于string中

发布时间:2020-12-13 13:22:16 所属栏目:PHP教程 来源:网络整理
导读:我有一个数组: ?php $array = [ 'fruits' = [ 'apple' = 'value','orange' = 'value' ],'vegetables' = [ 'onion' = 'value','carrot' = 'value' ]; 我也有一个字符串: $string = 'fruits[orange]'; 有没有办法检查字符串中指定的 – 数组键 – 是否存在于
我有一个数组:
<?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.
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读