xxxxxxxxxx
// Sample array
$array = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
// Key to check
$key = 'key2';
// Check if key exists
if (array_key_exists($key, $array)) {
echo "The key '$key' exists in the array.";
} else {
echo "The key '$key' does not exist in the array.";
}
xxxxxxxxxx
<?php
$search_array = array('first' => null, 'second' => 4);
// returns false
isset($search_array['first']);
// returns true
array_key_exists('first', $search_array);
?>
xxxxxxxxxx
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
xxxxxxxxxx
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
//output = a;
xxxxxxxxxx
<?php
$a=array("fruit"=>"Apple","Car"=>"BMW");
if (array_key_exists("Apple",$a)){
echo "Array Key exists!";
}else{
echo "Array Key does not exist!";
}
?>
xxxxxxxxxx
<?php
$exampleArray = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
$desiredKey = 'key2';
if (array_key_exists($desiredKey, $exampleArray)) {
echo "The key '$desiredKey' exists in the array.";
} else {
echo "The key '$desiredKey' does not exist in the array.";
}
?>
xxxxxxxxxx
<?php
$search_array = array('first' => null, 'second' => 4);
// returns false
isset($search_array['first']);
// returns true
array_key_exists('first', $search_array);
?>
xxxxxxxxxx
// Sample object
$myObject = (object) [
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
];
// Key to check
$key = 'key2';
// Check if key exists in the object
if(array_key_exists($key, get_object_vars($myObject))){
echo 'Key exists in the object.';
} else {
echo 'Key does not exist in the object.';
}
xxxxxxxxxx
function kPrint($key,$obj){
return (gettype($obj)=="array"?(array_key_exists($key,$obj)?$obj[$key]:("<font color='red'>NA</font>")):(gettype($obj)=="object"?(property_exists($obj,$key)?$obj->$key:("<font color='red'>NA</font>")):("<font color='red'><font color='green'>:::Exception Start:::</font><br>Invalid Object/Array Passed at kPrint() Function!!<br> At : Variable => ".print_r($obj)."<br>Key => ".$key."<br> At File: <font color='blue'>".debug_backtrace()[0]['file']."</font><br> At Line : ".debug_backtrace()[0]['line']."<br><font color='green'>:::Exception End:::</font></font>")));
}
//call this function in echo and pass parameters like key and array/object