Reputation: 241
I'm fetching data from a database that has some empty fields here and there, therefore I have some if statements in my code, but I can't seem to find the mistake in them. Here are some examples:
Get actual title (of candidate):
As you can see, there's the possibility that the field is at either place 5 or 6 in the array of a candidate.
if(array_key_exists(5, $FL) == true && $FL[5]->val == 'Actual title') {
$currentTitle = $FL[5]->content;
} else if (array_key_exists(6, $FL) == true && $FL[6]->val == 'Actual title') {
$currentTitle = $FL[6]->content;
} else {
$currentTitle = $notSpecified;
}
Here's how I get the skills:
if(array_key_exists(5, $FL) == true && $FL[5]->val == 'Kompetencer') {
$skills = $FL[5]->content;
$parts = explode(',', $skills);
$result = implode(', ', $parts);
$skills = $result;
} else if (array_key_exists(6, $FL) == true && $FL[6]->val == 'Kompetencer') {
$skills = $FL[6]->content;
$parts = explode(',', $skills);
$result = implode(', ', $parts);
$skills = $result;
} else {
$skills = $notSpecified;
}
I print these in a table. For some reason I can execute the code the first time, and it shows e.g. "CEO" as actual title, but not the associated skills. Then I can refresh 10 times or something and suddenly it doesn't show the title but only the skill. Skill and actual title are seperate columns in the table. Is there a hole in my logic somewhere?
It's really hard for me to figure it out since I don't get any error messages and I'm relatively new to PHP.
Upvotes: 0
Views: 45
Reputation: 352
Well, I have a couple of thoughts, but without seeing all the code and the query, it is a bit hard to tell.
First of all, I would recommend using === in your comparisons, rather than ==. This forces PHP, which is a weakly typed language to evaluate the variable type as well as value. Also, do not be afraid to throw some parentheses in your if statements as necessary to separate the boolean clauses you are testing.
Also, I am not understanding the reason behind exploding the string into an array, and then imploding it back into a comma delimited string. You could just use the original. Please let me know the thought process behind this.
The last thing is that you can turn error reporting on in the php.ini file. You will find this very helpful when you encounter a syntax error. Unfortunately, a logic, or algorithmic error will not be caught by the parser. You will just get unexpected results, which you are.
EDIT: I think the elseif structure might be leading to some ambiguity as you are testing for element 5 first, which should always be there, correct?
Please try this and let us know what you find:
//No need to test if $FL[5] exists. It always will.
if($FL[5]->val === 'Actual title')
{
$currentTitle = $FL[5]->content;
}
else //Must be 6, as it is not in 5
{
$currentTitle = $FL[6]->content;
}
This should eliminate any ambiguity of the application's decision making. Please let us know what you find.
Upvotes: 1