AND/OR comparisons starting from null, true, or false..? - php

I want to loop through a set of conditions, returning true only if every condition is met, collecting reasons along the way if not.
<?php
$dataval = 0;
$tests = [
[1,0,0,4,5],
[0,0,0,0,0]
];
foreach($tests as $condition) {
$retval = null;
$reasons = [];
foreach($condition as $item){
if($item == $dataval){
$retval == $retval && true;
} else {
$retval == $retval && false;
$reasons[] = "Failed to match " . $dataval . " to " . $item;
}
}
if($retval === true){
echo "All conditions met<br>";
} else {
echo "NOT all conditions met<br>";
}
echo "<pre>" . print_r($reasons, 1) . "</pre>";
}
?>
OUTPUT
NOT all conditions met
Array
(
[0] => Failed to match 0 to 1
[1] => Failed to match 0 to 4
[2] => Failed to match 0 to 5
)
NOT all conditions met
Array
(
)
No matter what the initial value of $retval, one or both tests is going to fail. If the initial value is true, both tests return true (which is incorrect); if false or null, then both return false (which is also incorrect).
Yes, I could break on the first false, but why the test failed is important, and it could fail for more than one reason so I shouldn't just break out of the loop as soon as the first failure is caught.
Is there a way to do this without adding another variable to tally up the hits and misses?

You need to initialize $retval to true. When you get a mismatch, set it to false and push the error onto the $reason array.
But don't really need the $retval variable. Just check if the array is empty.
foreach($tests as $condition) {
$reasons = [];
foreach($condition as $item){
if($item != $dataval) {
$reasons[] = "Failed to match " . $dataval . " to " . $item;
}
}
if(empty($reasons)){
echo "All conditions met<br>";
} else {
echo "NOT all conditions met<br>";
echo "<pre>" . print_r($reasons, 1) . "</pre>";
}
}

Related

validating array params via function

Why does myFunction() below validate the given parameter as true? This was caught by mistake as myFunction should normally receive the entire array as a parameter, but in this case only a specific value ("35") within the array was passed to the function. Yet, it still validated as true. What am I missing here as I would not expect the parameter to validate as true, it was passed a string, not an array?
$myVar = array('id' => '35');
myFunction($myVar['id']);
function myFunction($params) {
if (isset($params['id']) && !empty($params['id']) && $params['id'] == intval($params['id']) && $params['id'] > 0) {
echo "id is valid<br>";
echo "id = " . $params['id'] . "<br>";
echo "params = " . $params . "<br>";
print_r($params);
} else {
echo "id is invalid";
}
}
Output:
id is valid
id = 3
params = 35
35
You are not using strict comparison here $params['id'] == intval($params['id']) and PHP juggles with the types. Change it to $params['id'] === intval($params['id']).
Or use is_int() function.

how can i change the array value from if else statement inside a loop?

i've been hours trying to assign value in the array but every iteration the array is set to 0 and i can't understand why , here's the code ...
$AurQ = array();
$prod = '';
while ($NOTIFY = $notification->fetch_assoc()) {
print_r($AurQ);
if ($NOTIFY['notification_type_ID'] == 1) {
if (in_array($NOTIFY['qID'], $AurQ, true)) {
echo "exist";
continue;
} else {
$AurQ[] = $NOTIFY['qID']; // Adding the value to the array
$prod .= '<li><a href="http://localhost/website/link/' . $NOTIFY['qID'] . '"> <span class="AskIcon"></span><span class="noti_announce">';
$prod .= '<span class="unB">' . $NOTIFY['first_name'] . ' ' . $NOTIFY['last_name'] . '</span> ' . $NOTIFY['notify_name_en'] . ' "' . $NOTIFY['q_title'] . '"</span>';
$prod .= '<span class="noti_time"><span class="icon"></span>' . time_elapsed_string($NOTIFY['time']) . '</span></a></li>';
} // end of if doesn't exist in Array List
} //end of if
} // end of loop
The problem appears to be that you're pushing a value to the array only after checking if it already exists in that array, which it doesn't given that you're initializing it as an empty array just above it.
So, there's a logic error here, and depending on what you're trying to do, it can be fixed by moving the $AurQ[] = $NOTIFY['qID'] ; line into the else statement, or by changing your if statement from if (in_array($NOTIFY['qID'], $AurQ, true)) { to if (!in_array($NOTIFY['qID'], $AurQ, true)) {.
As you didn't mention an issue with things displaying when you didn't want them to, I'm going to assume you're looking for the former solution as opposed to the latter. So, your code will wind up looking something like this:
$AurQ = array();
$prod ='';
while($NOTIFY = $notification->fetch_assoc()) {
if ($NOTIFY['notification_type_ID'] == 1) {
if (in_array($NOTIFY['qID'], $AurQ, true)){ //If it's ALREADY in the array
echo "exist";
continue;
} else { //Otherwise we need to add it, and display it
$AurQ[] = $NOTIFY['qID'] ; // Adding the value to the array
$prod .= '<li><a href="http://localhost/website/link/'.$NOTIFY['qID'].'"> <span class="AskIcon"></span><span class="noti_announce">';
$prod .= '<span class="unB">'.$NOTIFY['first_name'].' '.$NOTIFY['last_name'].'</span> '.$NOTIFY['notify_name_en'].' "'.$NOTIFY['q_title'].'"</span>';
$prod .= '<span class="noti_time"><span class="icon"></span>'.time_elapsed_string($NOTIFY['time']).'</span></a></li>';
}// end of if doesn't exist in Array List
}//end of if
} // end of loop
Given your code you just need to move $AurQ[] = $NOTIFY['qID']; to else block.
Currently, $AurQ[] is empty and if block will never run because in_array($NOTIFY['qID'], $AurQ, true) will always return false.

How to use strpos in PHP?

function check($text){
if(strpos('a', $text) == FALSE && strpos('b', $text) == FALSE){
echo 'error';
} else {
echo 'ok';
}
}
echo check('text') . "\n";
echo check('asd') . "\n";
echo check('bnm') . "\n";
echo check('test') . "\n";
echo check('abc') . "\n";
live: http://codepad.org/W025YYuH
why this not working? This return:
1 error 2 error 3 error 4 error 5 error
but should be:
1 error 2 ok 3 ok 4 error 5 ok
You should use === FALSE instead of == FALSE, as explained in the documentation
Additionally, your arguments are in the wrong order. Again, consult the documentation (or, as some people say, RTM)
Invert the position of the argument, first argument is the string, second argument is what do you search into the string.
strpos ( 'The string to search in' ,'the argument of search' )
Then == would not work as expected
because the position of 'a' was the 0th (first) character.
Try this:
function check($text){
if(strpos($text, 'a') === FALSE && strpos($text, 'b') === FALSE){
echo 'error';
} else {
echo 'ok';
}
}
echo check('text') . "\n";
echo check('asd') . "\n";
echo check('bnm') . "\n";
echo check('test') . "\n";
echo check('abc') . "\n";
You have the arfuments the wrong way around, change to:
if(strpos($text, 'a') === FALSE && strpos($text, 'b') === FALSE){
Also note that you need to check for a boolean false with the identical operator (===)

If Its empty, return something in PHP

i have a code, it's getting data but when it gets nothing i want it to return something.
$upcoming = simplexml_load_file('http://api.website.com');
foreach($upcoming->trailer as $x => $updates) {
$content.= '<center><br><span> ' . $updates->embed . '</span></center>';
}
This is the code. It's getting data but when it got nothing, i would like it to say NO Videos.
How can i do that? I tried strlen() but i couldn't applied it.
I tried strpos but it didn't work either.
You can simply check the result of simplexml_load_file and act accordingly
if (false === $upcoming) {
echo "No Videos";
} else {
//your foreach loop here
}
$upcoming = simplexml_load_file('http://api.website.com');
if($upcoming == null || $upcoming == false){
$content = "No videos";
}
else{
foreach($upcoming->trailer as $x => $updates) {
$content.= '<center><br><span> ' . $updates->embed . '</span></center>';
}
}
Add some flag in your foreach to put a flag if anything has been printed or just check the $upcoming.
Then just check the flag and echo "no videos" your message.
Do it like this:
$Something=false;
$upcoming = simplexml_load_file('http://api.website.com');
foreach($upcoming->trailer as $x => $updates) {
if($updates->embed){
$Something=true;
}
$content.= '<center><br><span> ' . $updates->embed . '</span></center>';
}
if(!$Something){
echo "<center>No videos</center>";
}
Or:
$upcoming = simplexml_load_file('http://api.website.com');
if(!$upcoming){
echo "<center>No videos</center>";
}
else{
foreach($upcoming->trailer as $x => $updates) {
if($updates->embed){
$Soemthing=true;
}
$content.= '<center><br><span> ' . $updates->embed . '</span></center>';
}
}

trying to save time with PHP if/elseif statements

I have a rather big if statement:
if (!$result_spam)
{
$confrim_spam = "FAILED";
}
else if ($result_spam)
{
$confrim_spam = "PASSED";
}
if (!$result_email_manage)
{
$confrim_email_manage = "FAILED";
}
else if ($result_email_manage)
{
$confrim_email_manage = "PASSED";
}
if (!$result_analyt)
{
$confrim_analytics = "FAILED";
}
else if ($result_analyt)
{
$confrim_analytics = "PASSED";
}
Now I want to do another if statement to check if all have PASSED or if all have FAILED or is some have PASSED and some have FAILED and then echo (do something with) the failed ones.
I know how to check if all have passed or failed:
if ($confirm_spam == "PASSED" AND $confirm_analytics == "PASSED"
but to check if some have passed and some haven't and then find the ones that failed will take too long, right?
I was just wondering, would there be an easier/quicker way to do this?
Since they are all bools anyway:
if($result_spam && $result_email_manage && $result_analyt){
//do all passed
}
elseif($result_spam || $result_email_manage || $result_analyt){
//at least one passed
if(!$result_spam){ echo '$result_spam failed';}
if(!$result_email_manage){ echo '$result_email_manage failed';}
if(!$result_analyt){ echo '$result_analyt failed';}
}
else {
//do all failed
}
You can change validation logic to something like
$passed = array();
$failed = array();
if (!$result_spam)
{
array_push($failed, "confirm_spam");
}
else
{
array_push($passed, "confirm_spam");
}
...
Then you have an easy and clear way to check whether all passed/failed and which tests are failed.
What if you try this way:
$passed = $failed = "";
$all = array("confrim_spam" => $result_spam,
"confrim_email_manage" => $result_email_manage,
"confrim_analytics" => $result_analyt);
foreach($all as $a => $b)
{
if (!$b)
$failed.= $a . ", ";
else
$passed.= $a . ", ";
}
Then if var $passed is empty, none passed else if $failed is not empty, at last one have not passed.. so do you got what passed and what failed and do something with them. And you can store results both in a string or an array whatever you want...

Categories