Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array key exists from string

Tags:

arrays

string

php

I have an array:

<?php
    $array = [
        'fruits' => [
            'apple' => 'value',
            'orange' => 'value'
        ],
        'vegetables' => [
            'onion' => 'value',
            'carrot' => 'value'
    ];

I also have a string:

$string = 'fruits[orange]';

Is there any way to check if the - array key specified in the string - exists in the array?

For example:

<?php
if(array_key_exists($string, $array)) 
{
    echo 'Orange exists';
}
like image 262
CDR Avatar asked Sep 27 '17 09:09

CDR


Video Answer


1 Answers

Try this one. Here we are using foreach and isset function.

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.
}
like image 169
Sahil Gulati Avatar answered Oct 06 '22 23:10

Sahil Gulati