-1

I have a var like this...

$var = '["continent"]["country"]["province"]';

and I want to check if the var is a key in a array.

Here's what I've tried, unfortunately without success.

if (!isset($array.$var)) :
     do...
endif;

Is there a native PHP way to do this? I'm not a PHP wizard, Thanks!

3 Answers3

0

If the format is definitely like that, you can do something like this:

<?php
// Convert into a proper PHP array by trimming the extra stuff and exploding:
$var = '["continent"]["country"]["province"]';
$var = trim($var, '["');
$var = explode('"]["', $var);
// Apply native array functions...
$key = "country";
if (in_array($key, $var))
    // Do something if present
    echo "Present";
else
    echo "Not Present";
?>

Demo: http://ideone.com/tLx7c3

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

you can use
array_key_exists($key,$array)
to test if the key exists in an array.. eg .

<?php
$search_array = array('stack' => 1, 'overflow' => 2);
if (array_key_exists('stack', $search_array)) {
    echo "The element is in the array";
}
?>

array_key_exists() is a php method which returns TRUE if the given key is set in the array. key can be any value possible for an array index. You can refer the following document for this . http://php.net/manual/en/function.array-key-exists.php

shank
  • 91
  • 3
  • 13
0
<?php

$array = array(
    '["continent"]["country"]["province"]' => 'foo',
    '["big"]["fat"]["mama"]' => 'bar'
);

$var = '["continent"]["country"]["province"]';

if (array_key_exists($var,$array))
    print 'key is in the array';
Progrock
  • 7,373
  • 1
  • 19
  • 25