I have a function that is checking a value submitted by the user against a list of winning entries for a competition.
Currently if the user enters "1234" it’s returning false, even though the value is there, but if a user enters "5678" it returns true and sends back all the data associated with that entry.
Can anybody point out why it’s only finding the last value in the array true? I’ve tried a few different approaches, but nothing is working!
$entries = array(
(object) [
"uid" => "1234",
"item" => "x",
"text_prefix" => "x",
"text_suffix" => "x",
"prize_link" => "x",
"data_captcher" => true
],
(object) [
"uid" => "5678",
"item" => "x",
"text_prefix" => "x",
"text_suffix" => "x",
"prize_link" => "x",
"data_captcher" => false
],
);
// $data = json_encode($entries);
// echo $data;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$code = isset($_POST['code']) ? $_POST['code'] : '';
var_dump($code);
// foreach ($entries as $entry => $entry_Value) {
for ($x = 0; $x < count($entries); $x++) {
// var_dump($entry->uid);
if ($entries[$x]->uid == $code) {
$value = [
"uid" => $entries[$x]->uid,
"item" => $entries[$x]->item,
"text_prefix" => $entries[$x]->text_prefix,
"text_suffix" => $entries[$x]->text_suffix,
"prize_link" => $entries[$x]->prize_link,
"data_captcher" => $entries[$x]->data_captcher,
];
}else {
$value = 'false';
}
// var_dump($entries[$x]);
}
$data = json_encode($value);
echo $data;
}
>Solution :
It is very simple, you miss a stop condition.
Your loop iterates all entries, so the last entry will determine whether value is false or not.
What you should do is add break in your if condition:
if ($entries[$x]->uid == $code) {
$value = [
"uid" => $entries[$x]->uid,
"item" => $entries[$x]->item,
"text_prefix" => $entries[$x]->text_prefix,
"text_suffix" => $entries[$x]->text_suffix,
"prize_link" => $entries[$x]->prize_link,
"data_captcher" => $entries[$x]->data_captcher,
];
break; // <== this will stop the "for" loop
}else {
$value = 'false';
}
By the way, in your case I would use foreach loop for readability reasons:
foreach ($entries as $entry) {
:
:
}