Getting the values key in an array
I'm experiencing som difficulties to check if a key exists in an array or not. What I want to do is:
if(array_key_exists('hello',$myArray)) {
do stuff;
}
or:
if(isset($myArray['hello'])) {
do stuff;
}
But I think I am doing this in the wrong way, or something like that. I use variables as my keynames, so when I set the array key and value I do it something like this:
//myArray = an array with some random words
foreach($myArray as $item) {
if($item == 'hello') {
//Create a new array to put stuff in
$myNewArray[$item] = 1;
}
}
However, if I later want to check if if the key 'hello' exists (using a variable again, in an array, just for the sake 开发者_开发技巧of it):
$item[0] = 'hello';
$item[1] = 'hello again sir';
if(array_key_exists($item[0], $myNewArray)) {
echo 'The key exists!';
} else {
echo 'The key does not exists';
}
//Output: The key does not exists
So – any ideas on what I am doing wrong? Any good ways to approach this problem? And please note; I've already tried to use to put the needle between single quotation marks.
Update: Some output using var_dump() in my real code - http://pastebin.com/5N1ZWC9f - Still not really getting why it doesn't work as it should?
The function var_dump()
can always give you good insight into what exactly is in your array. That should help debugging your code. As for your example code, I think the problem is you're checking $myArray
where I think you want to be checking $myNewArray
;
if(array_key_exists($item[0],$myNewArray)) {
echo 'The key exists!';
} else {
echo 'The key does not exists';
}
In your last part:
if(array_key_exists($item[0],$myArray)) {
echo 'The key exists!';
} else {
echo 'The key does not exists';
}
You are searching in $myArray, not in $myNewArray. But that might not be your actual code. What do you see as keys in $myNewArray if you do:
print_r($myNewArray);
If 'hello' is there as key, then the script should echo 'The key exists!'
I think you are checking a key pair value. So 'Hello' is the value and '0' is the key. Try setting up the array as:
$myArray = ('hello' => 'This is the value');
if (array_key_exists('hello',$myArray) {
echo 'I exist!';
}
Try that.
Found out that the value wasn't a string, but an SimpleXML object, which made so that I couldn't compare them (naturally...). Beginners mistake from my side.
精彩评论