How do I clean up this if/else statement? (refactoring) - php

I know there must be a nicer way to do this, but whenever I search "&&" i don't get good enough results...
<?php
if (empty($row[ContactName]) && empty($row[ContactEmail]) && empty($row[ContactPhone]) && empty($row[Website])){
echo "Not Provided";
}
else{
...do stuff...
}
?>
Thanks!

What is wrong with the original code?
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
Looks like fine code to me...

<?php
$i=1;
$ar=array('ContactName','ContactEmail','ContactPhone','Website')
foreach($ar as $a)
if (empty($row[$a]))
{
$i=0;
break; //to make code fast
}
if($i) //do stuff
else echo 'not provided';
?>
or if you really want to make your code extra small then change your column name in database
From To
ContactName Col1
ContactEmail Col2
ContactPhone Col3
Website Col4
and then do
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
else echo 'Not Provided';
?>
However it is not good to rename column as it will make your db somewhat less understandable.

As php functions have a lot of inconsistency, It's always a good idea using a library to make it more consistent.
put this function in that library:
function empty()
{
foreach(func_get_args() as $arg) if (empty($arg)) return false;
return true;
}
usage:
if (empty($row[ContactName], $row[ContactEmail], $row[ContactPhone], $row[Website])) {
echo "Not Provided";
}

you could make it as short as this if compactness was more important than readability :)
$required = array('ContactName', 'ContactEmail', 'ContactPhone', 'Website');
$ra = array_filter(array_intersect_key($row,array_flip($required)));
if(empty($ra)){
echo "Not Provided";
}
else{
//....
}
you can't put array_filter inside empty() or you get "Fatal error: Can't use function return value in write context"
1) array flip is turning your $required values into keys
2) array_intersect_key throws away any $row keys not found in $required
3) array_filter throws away any empty values
leaving you with a zero length array, which is empty. No need to worry about array lengths or loops

<?php
$flag = 1;
if (empty($row[ContactName])){
$flag = 0;
}
if (empty($row[ContactEmail])){
$flag = 0;
}
if (empty($row[ContactPhone])){
$flag = 0;
}
if (empty($row[Website])){
$flag = 0;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
?>
OR
$flag = 1;
$i=0;
$mustarray = array('ContactName','ContactName','ContactName','ContactName'); //or any number of fields that you want as mandatory
foreach($yourresult as $row){
if(empty($row[$mustarray [$i]])){
$flag = 0;
}
$i++;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}

Do not play with making arrays and stuff just to make code look nicer.
As Tommy pointed
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
this code is nice, just need proper formatting like he pointed.
Making arrays and then launching loop will decrease performance
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
?>
this might look small, nice and "pro", but has more operations to give same results as a simple if instruction.
Not saying that it cant be done faster, i don't know php well, just remember about code executing speed.

Related

How do you make sure an array is empty in PHP?

Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php

How to select the next number in a loop?

The function for the primes is clear, so I omitted it.
$a=10;
$z=30;
for($prime = $a; $prime<$z; $prime++)
{ if
(Prim($prime) == TRUE)
{ echo $prime."<br/>";}}
Now I want to select the next term of the sequence as well, in order to perform an operation between the variable $prime and $next_prime, as long as the loop goes on - like for example:
$prime_gap=bcsub($next_prime, $prime);
Whatever solutions I find and I try, it's never the proper one. It's surely very simple but I am already desperate.
I would suggest you start by creating a next_prime() function. Like this, for example:
function next_prime($n) {
do {
$n++;
} while (!Prim($n));
return $n;
}
Then you can refactor your code quite easily:
$a=10;
$z=30;
for ($p1=next_prime($a),$p2=next_prime($p1); $p2<$z; $p1=$p2,$p2=next_prime($p2)) {
if (some_function($p1, $p2)) {
echo "I like $p1 and $p2\n";
}
}
The if I add in the for loop is not so nice, but if you want something simple and easy to understand, you can still use it (I switch the name from $prime & $next_prime to $prime & $previous_prime, I think it makes more sense)
$a=10;
$z=30;
$previous_prime = 0;
for($prime = $a; $prime<$z; $prime++)
{
if (Prim($prime) == TRUE)
{
echo $prime."<br/>";
if ($previous_prime == 0) {
$previous_prime = $prime
} else
{
$prime_gap = $prime - $previous_prime;
$previous_prime = $prime;
}
}
}

Is it possible to create a for loop inside an if condition?

I need to check if some text areas are set, but there might be a lot of them. I want to check if every single one of them is set inside an if statement with a for loop.
if(//for loop here checking isset($_POST['item'.$i]) )
You could do this:
// Assume all set
$allSet = true;
// Check however many you need
for($i=0;$i<10;$i++) {
if (!isset($_POST['item'.$i])) {
$allSet=false; // If anything is not set, flag it and bail out.
break;
}
}
if ($allSet) {
//do stuff
} else {
// do other stuff
}
If you've only a few, or they're not sequential there's no need for a loop. You can just do:
if (isset($_POST['a'], $_POST['d'], $_POST['k']....)) {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
try using this:
$post=$_POST;
foreach($post as $key=>$value){
if (isset($value) && $value !="") {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
You can try:
<?php
$isset = true;
$itemCount = 10;
for($i = 0; $i < $itemCount && $isset; $i++){
$isset = isset($_POST['item'.$i]);
}
if ($isset){
//All the items are set
} else {
//Some items are not set
}
I'm surprised that after three answers, there isn't a correct one. It should be:
$success = true;
for($i = 0; $i < 10; $i++)
{
if (!isset($_POST['item'.$i]))
{
$success = false;
break;
}
}
if ($success)
{
... do something ...
}
Many variation are possible, but you can really break after one positive.
Yes, one may have a loop within an if-condtional. You may use a for-loop or you may find it more convenient to use a foreach-loop, as follows:
<?php
if (isset($_POST) && $_POST != NULL ){
foreach ($_POST as $key => $value) {
// perform validation of each item
}
}
?>
The if conditional basically tests that a form was submitted. It does not prevent an empty form from being submitted, which means that any required data must be checked to verify that the user provided the information. Note that $key bears the name of each field as the loop iterates.

How can I place text that relates to a foreach function, outside the loop?

I'm really unsure how to describe this, so please forgive me.
Basically, I'm reading from an XML, and then generating an IF statement that checks all records in the XML and if a condition matches, details about that record is displayed.
What I want to add, is a similar function but in reverse, but outside the foreach loop, so it's only displayed once.
foreach($xml as $Reader) { $items[] = $Reader; }
$items= array_filter($items, function($Reader) use ($exclude) {
if($Reader->Picture == 'None' || in_array($Reader->Pin, $exclude)) {
return false;
}
return true;
});
usort ($items, function($a, $b) {
return strcmp($a->Status,$b->Status);
});
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
}
}
if (!$items) { echo "Please check back in a moment when our readers will be available!"; }
So, in the XML file each Reader has a Status that can be one of three values: Available, Busy or Logged Off.
So what I'm doing, is for each record in the XML, checking if the Reader status is available.. and if so, echo the above line.
But I want to add in, that if NONE of the readers show as 'Available' to echo a single line that says 'Please check back in a moment'.
With the code above, ifthere are four readers online, but they're all busy.. nothing is displayed.
Any ideas?
Just use a simple boolean value
$noneAvailable = true;
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$noneAvailable = false;
}
}
if ($noneAvailable) {
echo "Please check back in a moment";
}
I managed to take the answer given above, and combine it with XPath to just filter the records in the XML based on the status given using xPath.
include TEMPLATEPATH."/extras/get-readers.php";
$readers = $xml->xpath('/ReaderDetails/Reader[Status="Available"]');
$gotOps = false;
foreach ($readers as $Reader)
{
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$gotOps = true;
}
if ($gotOps!=true)
{
echo 'Please check back in a moment when our readers will be available!';
}

Problem with Boolean Values in PHP

I've some problems with handling Boolean values in PHP. It is a validation script before storing data into database. I wrote a global validator that will validate and return a Boolean value whether the validation was successful .
Here is my code.
//VALIDATE
$isValid = true;
foreach($team as $key=>$val) {
if(!is_array($val)){
$isValid = $isValid && validate($val, $key);
}
}
for($it=0;$it<count($team['members']);$it++){
foreach($team['members'][$it] as $key=>$val) {
$isValid = $isValid && validate($val, $key);
}
}
if(!$isValid) { // EDITED: if(!isValid)
echo "validation error";
exit(1);
}
//END OF VALIDATE
The validate function is working properly but sometimes I end up getting $isValid = true or the other way, when I try with some test cases.
Hmm.. What am I doing wrong here ?
Please check, if this form does the trick:
if( false === $isValid) {
echo "validation error";
exit(1);
}
Note, that ( ! $isValid ) or (false == $isValid ) in some cases return results, which are at first look wrong. See for example the hint in the strpos() documentation.
In fact, the results are fine, since operations line ! or == try to cast operands in a 'useful' way.
That said, it's always better to user the === operator, since it checks values and types of operands. Please see operator overview.
if(!isValid) { falls back to if (!"isValid"), if there is no constant isValid. You probably meant if (!$isValid) {.
if(!isValid) {
isValid has no dolar, (you need to give variables in PHP some cash) so:
if(!$isValid) {
Source : http://bit.ly/1hxDmVR
Here is sample code for working with logical operators in PHP. Hope it will helpful:
<html>
<head>
<title>Logical</title>
</head>
<body>
<?php
$a=10;
$b=20;
if($a>$b)
{
echo " A is Greater";
}
elseif($a<$b)
{
echo " A is lesser";
}
else
{
echo "A and B are equal";
}
?>
<?php
$c=30;
$d=40;
//if(($a<$c)AND($b<$d))
if(($a<$c)&&($b<$d))
{
echo "A and B are larger";
}
if(isset($d))
$d=100;
echo $d;
unset($d);
?>
<?php
$var1=2;
switch($var1)
{
case 1:echo "var1 is 1";
break;
case 2:echo "var1 is 2";
break;
case 3:echo "var1 is 3";
break;
default:echo "var1 is unknown";
}
?>
</body>
</html>
I think the problem is that your $isValid variable can be changed many times in the loops and by the end of your code simply applies to the last value in your final loop.
You should set it to true initially and then only set it to false IF your validity check fails - not simply assign its value based on every single validity check.

Categories