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;
}
My Answer:
a winning entry, the function returns true. However, I want to modify the function to check if the user's entry is in an array of objects that contain the winning entries.
Here is an example of the array of objects:
php
$winningEntries = [
(object) ['entry' => '123'],
(object) ['entry' => '456'],
(object) ['entry' => '789']
];
And here is the function that checks if the user's entry is a winning entry:
php
function checkWinningEntry($userEntry, $winningEntries) {
foreach ($winningEntries as $entry) {
if ($entry->entry == $userEntry) {
return true;
}
}
return false;
}
You can use this function by passing the user's entry and the array of winning entries as arguments. For example:
php
$userEntry = '456';
if (checkWinningEntry($userEntry, $winningEntries)) {
echo 'Congratulations! You are a winner!';
} else {
echo 'Sorry, you did not win this time.';
}
This modified function will now check if the user's entry is in the array of objects containing the winning entries and return true if it is found.
Rate this post
4 of 5 based on 7504 votesComments