PHP array key exists from string

Viewed 1972

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';
}
5 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.
}

It would be a lot easier to check the other way around. As in check if the key is in the string. Since keys are unique, there's no way you have duplicates.

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

$string = 'fruits[orange]';

$keys = array_keys($array['fruits']);

foreach($keys as $fruit) {
  if(false !== stripos($string, $fruit)) {
    return true;
  }
}

While this solution is not necessarily ideal, the problem to begin with isn't exactly common.

You can explode and check the indices of the array.

$array = array(
    'fruits' => [
        'apple' => 'value',
        'orange' => 'value'
    ],
    'vegetables' => [
        'onion' => 'value',
        'carrot' => 'value'
]);

$string = 'fruits[orange]';

$indexes = (preg_split( "/(\[|\])/", $string));
$first_index= $indexes[0];
$seconnd_index= $indexes[1];
if(isset($array[$first_index][$seconnd_index]))
{
    echo "exist";
}
else
{
    echo "not exist";
}

DEMO

You can walk recursively:

$array = [
    'fruits' => [
       'apple' => 'value',
       'orange' => 'value'
    ],
   'vegetables' => [
       'onion' => 'value',
       'carrot' => 'value' 
    ]
];
$exists = false;
$search = "orange";
array_walk_recursive($array, function ($val, $key) use (&$exists,$search) {
     if ($search === $key) { $exists = true; }
});
echo ($exists?"Exists":"Doesn't exist");

Prints:

Exists

Example: http://sandbox.onlinephpfunctions.com/code/a3ffe7df25037476979f4b988c2f36f35742c217

Instead of using regex or strpos like the other answers, you could also simply split your $string on [ and resolve the keys one by one until there's only one key left. Then use that last key in combination with array_key_exists() to check for your item.

This should work for any amount of dimensions (eg fruit[apple][value][1]).

Example:

<?php

$arr = [
    'fruits' => [
        'orange' => 'value'
    ]
];

// Resolve keys by splitting on '[' and removing ']' from the results
$keys = 'fruits[orange]';
$keys = explode("[", $keys);
$keys = array_map(function($s) {
    return str_replace("]", "", $s);
}, $keys);

// Resolve item.
// Stop before the last key.
$item = $arr;
for($i = 0; $i < count($keys) - 1; $i++) {
    $item = $item[$keys[$i]];
}

// Check if the last remaining key exists.
if(array_key_exists($keys[count($keys)-1], $item)) {
    // do things
}
Related