I've build my nice page in PHP, but I would like to get a different output order based on the result of a if condition applied at the beginning of the page.
IE:
if(condition is true){
block n1
block n2 }
else{
block n2
block n1 }
Can you kindly advise on what's the best practices in this case?
I think a flag should solve the problem, but I'm struggling to understand how.
You could prepare you blocks and then exactly what you wrote :
$block1 = "12345";
$block2 = "67890";
$inverted = true;
if ($inverted===true) {
echo $block2.$block1;
} else {
echo $block1.$block2;
}
There are several approaches to this. One would be with if and else and if you have many possibilities, then switch case would be advisable.
$check = 1;
if( $check === 1) {
echo `show 1`;
} else {
echo 'It is not 1';
}
// OR
switch($check) {
case 1:
echo 'Show 1';
break;
case 2:
echo 'Show 2';
break;
case 3:
echo 'Show 3';
break;
default:
echo 'It is not 1,2,3';
}
u can use array just like that
$orders = ['a', 'b'];
if (1 === 1) {
$orders = ['b', 'a'];
}
with this you don't need "else" part
foreach ($orders as $order){
echo $order."<br/>";
}
Related
I am in the making of some code that needs to check if a users login details are correct, and I therefore need a lot of if-statements inside each other. If any of the conditions in the if-statements are not true, they should alle return the same value. Is there an easy way of doing this, instead of writing the same multiple times? I have made an example below to visualize my problem. As you can see here I write " else { return false; }" multiple time, and this is what I am wondering if you are able to do more efficiently. Maybe so I only have to write "or else return false" once.
//some code
if (/*some condition*/) {
//some code
if (/*some new condition*/) {
//some code
if (/*some new condition*/) {
//some code
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
I am having a hard time finding a good way to explain my problem, so if you have a more elegant way of explaining it, do not hesitate to edit my post. I am also not quite sure that the title is as good as it could be, so if you have any ideas to an alternativ please say so :)
Lets say you have something like that (I added No):
if ( condition1 ) {
//some code 1
if ( condition2 ) {
//some code 2
if ( condition3 ) {
//some code 3
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
Since each time a condition is false, you exit the function returning false, you can directly test if the condition is false using a negation (if the negated condition is true):
if ( !condition1 ) {
return false;
}
//some code 1
if ( !condition2 ) {
return false;
}
//some code 2
if ( !condition3 ) {
return false;
}
//some code 3
This doesn't reduce the number of if statements, but you avoid many nesting levels and the else statements.
You can also try the switch statement. For many situations it will produce cleaner code.
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
The switch statement is also compatible with using strings:
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
}
?>
Good luck! :)
is it possible to simplify this code? I am trying to put all cases in a switch but always d break in the first case and i need all echo's in the html. What is possible? Thank you!
$resultservices = mysqli_query($connecDB,"SELECT * FROM clients WHERE id_client = $id_client");
while($rowservice = mysqli_fetch_array($resultservices)){
$php = (int)$rowservice['php'];
$java = (int)$rowservice['java'];
$ruby = (int)$rowservice['ruby'];
$node = (int)$rowservice['node'];
}
// Values can be "1" or "0". Example: php:1, java:1, ruby:0, node:1
switch ($php) {
case 0: break;
case 1: echo "<li>php</li>"; break;
}
switch ($java) {
case 0: break;
case 1: echo "<li>java</li>"; break;
}
switch ($ruby) {
case 0: break;
case 1: echo "<li>ruby</li>"; break;
}
switch ($node) {
case 0: break;
case 1: echo "<li>node</li>"; break;
}
While I'm not sure what you're trying to do, how about:
$resultservices = mysqli_query($connecDB,"SELECT * FROM clients WHERE id_client = $id_client");
while($rowservice = mysqli_fetch_array($resultservices)){
$service[1] = (int)$rowservice['1'];
$service[2] = (int)$rowservice['1'];
$service[3] = (int)$rowservice['0'];
$service[4] = (int)$rowservice['1'];
}
foreach ($service as $k=>$v) {
if ($v) {
echo "<li>service".$k."</li>";
}
}
[edit] I see we've got some new variables.
while($rowservice = mysqli_fetch_array($resultservices)){
$service['php'] = (int)$rowservice['php'];
$service['java'] = (int)$rowservice['java'];
$service['ruby'] = (int)$rowservice['ruby'];
$service['node'] = (int)$rowservice['node'];
}
foreach ($service as $k=>$v) {
if ($v) {
echo "<li>".$k."</li>";
}
}
Although really, all you're doing is outputting the last row of your MySQL, so you could also do
$resultservices = mysqli_query($connecDB,"SELECT * FROM clients WHERE id_client = '".mysqli_real_escape_string($connecDB, $id_client)."' ORDER BY id DESC LIMIT 1");
while($rowservice = mysqli_fetch_array($resultservices)){
if ($rowservice['php']) {
echo "<li>php</li>"
}
if ($rowservice['java']) {
echo "<li>java</li>"
}
if ($rowservice['ruby']) {
echo "<li>ruby</li>"
}
if ($rowservice['node']) {
echo "<li>node</li>"
}
}
Given that 3 of your four service values are going to have the SAME value, you could eliminate 2 of the switches and end up with the same results:
$service01 = (int)$rowservice['1'];
$service02 = (int)$rowservice['1']; // identical to service01
$service03 = (int)$rowservice['0'];
$service04 = (int)$rowservice['1']; // identical to service01
meaning you could have:
switch($service01) {
case 0: break;
case 1: echo "<li>service01, 02, and 04</li>"; break;
}
And then, assuming these values will never be anything but true/false 0/1 values, you could eliminate the switches entirely and go with a conventional if:
if ($service01) {
echo "service 01, 02 and 04";
}
I have an array of conditions :
$arrConditions = array ('>=2', '==1', '<=10');
...which I want to be able to use in an if...statement.
IE.
if (5 $arrConditions[0])
{
...do something
}
...which would be the same as :
if (5 >= 2)
{
...do something
}
Any help?
Thanks
Such a requirement is a sure sign of a bad design.
Most likely you can do that another, more usual way.
Nevertheless, never use eval for such things.
At least store each operator in pairs - an operator and operand.
$arrConditions = array (
array('>=',2),
array('==',1),
array('<=',10),
);
and then use switch:
list ($operator,$operand) = $arrConditions[0];
switch($operator) {
case '==':
$result = ($input == $operand);
break;
case '>=':
$result = ($input >= $operand);
break;
// and so on
}
But again - most likely you can solve it another, much easier way.
What about this ?
<?php
$arrConditions = array('==2', '==9', '==5', '==1', '==10', '==6', '==7');
$count = 0;
$myval = 0;
foreach ($arrConditions as $cond) {
$str = "if(5 $cond) { return $count;}";
$evalval = eval($str);
if (!empty($evalval)) {
$myval = $count;
}
$count++;
}
switch ($myval) {
case 0: echo '==2 satisfied';
break;
case 1: echo '==9 satisfied';
break;
case 2: echo '==5 satisfied';
break;
case 3: echo '==1 satisfied';
break;
case 4: echo '==10 satisfied';
break;
default : echo 'No condition satisfied';
}
?>
Good day guys,
I've made a sweet favorites function with php mysql and ajax, and its working great. Now I want to show 'favorite' when favorite = 0 and show 'unfavorite' when favorite = 1
if ($favorites == 0) {
$favorite = 'Favorite';
}
if ($favorites == 1) {
$unfavorite = 'unFavorite';
}
and echo it in the row as :
<div id="favorites">' .($favorite). ' ' .($unfavorite). '</div>
The problem is: when favorite = 0, both $favorite and $unfavorite are being shown. When favorite = 1 only $unfavorite is being shown correctly. Of course it should be $favorite OR $unfavorite. I assume the problem is clear and simple to you, please assist :)
Thanks in advance
It's easier to use just one variable:
$text = ''
if ($favorites == 0) {
$text = 'Favorite';
} else {
$text = 'unFavorite';
}
...
echo $text;
If you want to check $favorite, you are using the wrong variable in your control statement. Also, it is better coding practice to use elseif rather than if for that second if. One more thing: it's easier to manage one resulting variable.
$output = "";
if ($favorite == 0) {
$output = 'Favorite';
}
elseif ($favorite == 1) {
$output = 'unFavorite';
}
...
echo $output; // Or whatever you want to do with your output
Is $favorites an integer?
Anyway try using three equal signs (===) or else instead of the second if:
if ( $favorites === 0 )
{
// ...
}
else // or if ($favorites === 1)
{
// ...
}
You're making a toggle, so you only need one variable:
if(empty($favourites)){
$fav_toggle = 'Favorite';
} else {
$fav_toggle = 'unFavorite';
}
echo $fav_toggle;
Same code is working on me if I assigned $favorites = 0; or $favorites = 1;
You can also use if else
$favorites = 1;
if ($favorites == 0) {
$favorite = 'Favorite';
}
else if ($favorites == 1) {
$unfavorite = 'unFavorite';
}
I'm attempting to optimise the following PHP If/Else statement. Could I rewrite the code to make use to case and switch, or should I leave it as it is, or what?
Code:
if(empty($_GET['id'])){
include('pages/home.php');
}elseif ($_GET['id'] === '13') {
include('pages/servicestatus.php');
}elseif(!empty($_GET['id'])){
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if(!$rawdata){
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
}else{
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if(!$rawdata){
error_404();
}
}
Thanks
I hate switch statements, but its personal preference to be honest. As far as further optimization i'd suggest taking a look at some form of assembly language. It will give you some general ideas on how to make conditional statements more efficient. That is, it will give you a different out look on things.
if(!empty($_GET['id']))
{
if($_GET['id'] == '13')
{
include('pages/servicestatus.php');
}
else
{
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if (!$rawdata) {
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
} else {
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if (!$rawdata) {
error_404();
}
}
}
else
{
include('pages/home.php');
}
switch would be appropriate if you had several discrete values for $_GET['id'] that you were checking for.
One suggestion I can make for the sake of readability is that
} elseif (!empty($_GET['id'])) {
only needs to be
} else {
Well i don't think it's necessary to switch to a swith
but you could change
} elseif (!empty($_GET['id'])) {
to just
}else{
You may want to look into breaking up your code into a MVC form; that would make it much easier to maintain your code. At least put the last clause into another file, probably called default.php and include it. Also, you might create an array of id => file key/value sets, lookup the id, and include the file.
if (isset($_GET['id'])) {
$pages = array(
0 => 'home.php',
13 => 'servicestatus.php'
);
if (isset($pages[$_GET['id']])) {
include('pages/' . $pages[$_GET['id']]);
} else {
include('pages/default.php');
}
}
Yes, switch is evaluate once, is efficient than if elseif,
and is easier to maintain with this given structure
switch ($_GET['id'])
{
case 13: ... break;
case 0 : ... break;
default: ... break;
}
I dont know, if you should, or should not, but here I wouldnt. The main reason is, that there is at least one statement, you can omit, and then, you will have just a if-elseif-else-Statement
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
elseif (!empty($_GET['id'])) { /* code* }
is the same as
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
else { /* code* }
In the block after that, the statement if(!$rawdata) is also duplicated.