7

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';
}
4
  • 3
    It's strange to parse a string like $string to read an array. With two parameters, $type and $name your problem will be easier Commented Sep 27, 2017 at 9:40
  • Agreed - if the format of the string is under your control, then consider using something easier to parse. Commented Sep 27, 2017 at 9:41
  • $string value is dynamic or not? Commented Sep 27, 2017 at 9:51
  • $str = explode(']',explode('[', $string)[1])[0]; array_walk_recursive($array, function($k, $v, $str){ if($v == $str){ echo " $str found"; } }, $str); Commented Sep 27, 2017 at 9:56

5 Answers 5

4

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.
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

So what happens if the OP tries to look up fruits[pineapple] but the array only has the key apple? I think your solution needs some further tweaking. (Also, it scales rather poorly if the arrays might have a huge number of keys.)
1

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

Comments

1

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
}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.