Filled array detected as true [duplicate] - php

This question already has answers here:
PHP "If true" test on array always returns true?
(1 answer)
Is an array considered as boolean true in php?
(6 answers)
Closed 2 years ago.
I receive an array from a method, and I check the value of it. If the array equals to true, it should do something, but if not, it has to do something else. Here's my if statement :
$existence_status = $model->getReportExistenceStatus($validFormData['start_date'], $validFormData['end_date'], $validFormData['start_hour'] . ":00", $validFormData['end_hour'] . ":00");
var_dump($existence_status);
if ($existence_status) {
// Report was not found, continue processing a complete API request
// Get the report from the model
$report_data = $model->getReport($validFormData['start_date'], $validFormData['end_date'], $validFormData['start_hour'], $validFormData['end_hour'], $access_token);
// Set the data on the chart
if ($report_data !== false) {
$chart_status = true;
$start_date = $validFormData['start_date'];
$end_date = $validFormData['end_date'];
$start_hour = $validFormData['start_hour'];
$end_hour = $validFormData['end_hour'];
$success = $report_data['success'];
$failed = $report_data['failed'];
} else {
$chart_status = false;
}
} else {
// Report was found, get the data and print them
$chart_status = true;
$start_date = $validFormData['start_date'];
$end_date = $validFormData['end_date'];
$start_hour = $validFormData['start_hour'];
$end_hour = $validFormData['end_hour'];
$success = $existence_status['success'];
$failed = $existence_status['failed'];
}
I just found out that if the returned value from the call of the getReportExistenceStatus is an array, it will go in the if instead of the else.
Here is the value of the $existence_status (got it from the var_dump) :
array (size=2)
'success' => int 100
'failed' => int 0
But it still goes in the if statement instead of the else.
I've found a way to get around that problem (I'm using php !is_array($existance_status) as condition), but that really perturbate me, because, afaik, an filled array is not considered as "true", no ?
Is that normal ?

Related

Php date validation not working when typing 0 before the date [duplicate]

This question already has answers here:
why string is greater or less than the integer?
(3 answers)
Closed 3 years ago.
I have this function to validate the date of birth and send back error message when date is correct or not.
Here is my function
function checkBirthDate($string)
{
$matches = array();
$pattern = '/^([0-9]{1,2})\\/([0-9]{1,2})\\/([0-9]{4})$/';
if (!preg_match($pattern, $string, $matches)) return false;
if (!checkdate($matches[2], $matches[1], $matches[3])) return false;
return true;
}
//Get Parameters Passed From the JS Call to This Script
$fieldValue = $_GET["q"];
$fieldName = $_GET["q2"];
$fieldCheckBox = $_GET["q3"];
//Validate the DOB
if ($fieldName == 'stepbirth') {
$response = "";
foreach (explode(",", $fieldValue) as $dateString) {
//echo $dateString;
$birthDateLen = strlen($dateString);
if ($dateString > 9) {
if (checkBirthDate($dateString)) {
//Get last 4 characters of the Date for the Year
$year = substr($dateString, -4);
if ($year > 1900) {
//Get Timestamp passed over
$dt = DateTime::createFromFormat('d/m/Y', $dateString);
$userDate = $dt->getTimestamp();
//Get Date 1 Year from Today
$yearTime = date(strtotime('+100 year'));
//If User's Date is Within 1 Year
if ($userDate < $yearTime) {
$response .= '{"code":1,"message":""},';
} else {
$response .= '{"code":0,"message":"Fill date till 365 from now"},';
}
} else {
$response .= '{"code":0,"message":"Fill date after 1900"},';
}
} else {
$response .= '{"code":0,"message":"Fill valid date in."},';
}
} else {
$response .= '{"code":0,"message":""},';
}
}
$response = substr($response, 0, -1);
echo "[" . $response . "]";
}
Which is working fine and sending the correct response, but it has only one issue, while date starts at 0 like 01,02,03 till 09. It does not validate it always sends response code "0" and do not show error message in response, even the complete date of birth is not correct like 01/20/2018 here month is not correct. But when date starts 11/20/2018 it does correct validation and sends response code "1" and shos the message.
Can anyone help with this what I am doing wrong here?
Why not using strtotime for you value?
PHP will try to convert the date for you.
By using date("Y", strtotime($dateString)) returns the year for you. In your case you can use the time to validate or do your things with the date.
Further by using json_encode() you can pass an array which results in an json response. So:
$response = array("code" => 1, "message" => "Just a message");
$actual = json_encode($response);
echo $actual; //Returns { "Code": 1, "Message": "Just a message" }

avoid repeating variable due to undefined variable error

I'm trying to make a profile completion progress, which shows the percentage of how much a user has completed his profile settings. If a user has filled in a field, he receives +15 or +5, however, if the field is not filled in he receives +0.
the code I did is really bad, with variable repetitions, I wanted to know if you knew a cleaner way to do this.
if (!empty($user->avatar)) {
$avatar = 15;
} else { $avatar = 0; }
if (!empty($user->copertina)) {
$copertina = 15;
} else { $copertina = 0; }
// dati personali
if (!empty($user->name)) {
$name= 5;
} else { $name = 0; }
if (!empty($user->last_name)) {
$last_name = 5;
} else { $last_name = 0; }
[...]
if (!empty($user->biografia)) {
$biografia = 5;
} else { $biografia = 0; }
$personal = $avatar+$copertina+$name+$last_name+$sesso+$nascita;
$gaming = $steam+$battlenet+$xbox+$playstation+$switch+$uplay+$origin+$ds;
$social = $twitter+$facebook+$biografia;
$punti = $personal+$gaming+$social;
how do I remove all the others {$ variable = 0}?
You can't really, since you want the value to be a number, and not "undefined". You could initialize your variables to 0 like in this answer stackoverflow.com/questions/9651793/….
If you want to get into type comparisons for null variables, check php.net/types.comparisons. I would just initialize the variables to 0 and remove all the else.
OR...
modify your $user object to have all these variables in an array ($key:$value). You can then initialize the array to 0 all over, and modify it. Adding a new profile value would be easy, and adding array values is quick.
This snippet :
if (!empty($user->avatar)) {
$avatar = 15;
}
else {
$avatar = 0;
}
is semantically equivalent to :
$avatar = (bool)$user->avatar * 15;
Explanation:
Non-empty field gets converted to true and empty string or null gets converted to false
Because we do multiplication php true/false values gets converted to 1/0
So after multiplication you get 15 * 1 or 15 * 0 - depending if your field was used or not.

Identical Strings in PHP not matching [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 7 years ago.
I'm trying to compare two strings (one from my database and another supplied by the user) and see if they match! The problem I'm having is that they don't seem to match - even though the strings seems to be exactly identical?
My PHP code is below:
public function Verify($pdo, $id, $token) {
$prepsql = $pdo->prepare("SELECT * FROM Profiles WHERE id = '$id' LIMIT 1");
$prepsql->execute();
$currentrow = $prepsql->fetch();
$current = preg_replace("/[^a-zA-Z0-9]+/", "", $currentrow["token"]);
echo '<p>'.var_dump($current).'</p>';
echo '<p>'.var_dump($token).'</p>';
$token = preg_replace("/[^a-zA-Z0-9]+/", "", $token);
if ($current == null || $current = "") {
return false;
} else {
if (strcmp($token, $current) == 0) {
return true;
} else {
return false;
}
}
}
And here is the webpage output:
string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p>string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p><p>Not authenticated</p>
Not authenticated just means that this function is returning false...
What on earth am I doing wrong? As per advice given on other similar Stack Overflow answers, I've used the regex function to basically only keep alphanumeric characters but that has made no difference? It isn't a trimming issue either as that didn't work!
Any help would be much appreciated!
Thanks!
Here is your problem:
if ($current == null || $current = "") {
// ^ now `$current` is "", an empty string
You assign a new value to $current, an empty string.
You probably want something like:
if ($current == null || $current == "") {
// ^^ now you are comparing

PHP statement is not evaluating to what I was expecting [duplicate]

This question already has answers here:
Why does PHP consider 0 to be equal to a string?
(9 answers)
Closed 7 years ago.
I have the following code:
<?php
$starting_id = 0;
$params = array ('val' => $starting_id);
echo parse_params ($params);
function parse_params ($params)
{
$query = ' WHERE ';
if ($params['val'] === NULL) {
$query .= ' IS NULL';
return $query;
}
if ($params['val'] == 'NOT NULL') {
$query .= ' IS NOT NULL';
return $query;
}
return $query.' = '.$params['val'];
}
When I run it, I expect to see this:
WHERE
instead, I get the following:
WHERE IS NOT NULL
Any ideas why?
According to the PHP type comparison tables,
$var = 0 ; // (int)
if you compare $var == "string",
it will return true, you need to type check for this
$var === "string"
check php type comparison

How to check equal of value arrays in JSON by PHP

I want to check two arrays. If the value of one array anybody equal then $response:1 and otherwise for $response:0
example arrays:
{"data_comment":[{"name":"a"},{"address":"b"},{"age":"16"}]}
{"data_comment2":[{"name":"b"},{"address":"e"},{"age":"18"}]}
file php :
if($data_comment==$data_comment2){
$response2["success"] = "1";
// echoing JSON response
echo json_encode($response2);
} else {
$response2["success"] = "0";
$response2["message"] = "Error";
// echoing JSON response
echo json_encode($response2)
}
so , if any value of data_comment is same with data_comment2 value, then result will be false [$response2["success"] = "0"; ]..
but with my code, result always show [$response2["success"] = "1"; ] , there's is not same value at all between data_comment and data_comment2 .
thanks for any advice

Categories