Turn php loop output to variable? - php

I am still learning php and this is how i convert php loop statement output to variable::
ob_start();
if 2 > 1 {
echo 'It is OK';
} else {
echo 'It is not OK';
}
$myvar = ob_get_clean();
echo $myvar;
Now the $myvar will output above if result, but is there better approach in doing this?

First, there is no looping in your code: if/else blocks are executed once, not in a loop.
Second, if you want to save the string, you can assign it to your variable directly, using many approaches:
if/else
if(2 > 1) $myVar = 'it is OK';
else $myVar = 'it is not OK';
switch case
switch (2>1):
case true:
$myVar = 'it is OK';
break;
default:
$myVar = 'it is not OK';
endswitch;
ternary operator
$myVar = 2>1 ? 'it is OK' : 'it is not OK';

Related

Change order of output based on if condition

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/>";
}

Switch statement unusual behaviour

echo get_option('bp-username-field'); and echo get_option('bp-email-field'); respectively outputs checked and 0. but with this code both the cases are running. i.e. both hello from username and hello from email are dispayed.
switch("checked")
{
case get_option('bp-username-field'):
echo 'hello from username';
case get_option('bp-email-field'):
echo 'hello from email';
...
}
And if i change switch("0") it only echoes hello from email. Also, with swith(0) both case are running. What is this behaviour?
You have to add a break after the case. If not all cases will be executed. That is normal behavior for switch Statements
switch("checked")
{
case get_option('bp-username-field'):
echo 'hello from username';
break;
case get_option('bp-email-field'):
echo 'hello from email';
...
}
You are probably missing break
switch("checked")
{
case get_option('bp-username-field'):
echo 'hello from username';
break;
case get_option('bp-email-field'):
echo 'hello from email';
break;
...
}
When the first case gets executed, then you need to break the switch. You need to introduce break to break execution of rest of the cases that follows the selected case.
When switch(0) was called, it is the final case (as of here), so it doesn't execute the one before the second case.
switch/case does loose comparison. That's mean that "checked" == 0 is true. What you want to do is:
switch(true)
{
case get_option('bp-username-field') === "checked":
echo 'hello from username';
case get_option('bp-email-field') === "checked":
echo 'hello from email';
...
}
But in a switch statement, the condition is evaluated only once and the result is compared to each case statement. This mean that after the first case is evaluate as true, all the other case will be executed until the end of the switch. What you really want it:
if (get_option('bp-username-field') === "checked") {
echo 'hello from username';
}
if (get_option('bp-email-field') === "checked") {
echo 'hello from email';
}
Because your statement is wrong;
you should compare the variable what ever it is inside switch(variable) to all those cases. for example.
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}

if statement says true to a null variable

What is happening here? Is it to late for my brain?
I have a php file containing exaclty the code below.
<?php
$foo = 'foo';
$bar = null;
switch ($foo) {
default:
case 'foo':
if ($bar) {
echo 'true';
} else {
echo 'false';
}
}
Prints true when run in the browser but false when run on command line... HOW? I noticed when I remove the line default: it works, but how should this whole switch statement be related to this? It's still a simple if (null) { doing this anyway }
PHP 7.0.13
Apache/2.4.18
And yes... I cleared my browser cache, hit ctrl+f5... I even changed the scripts file name.
UPDATE:
After making changes to this simple file... (just adding whitespaces to the end) and hitting f5 in the browser it says false once but than true again... no matter what I do. I really don't get it.
UPDATE:
My PHP version just got updated from 7.0.13 to 7.0.15. Guess what... still the same output:
Apache/Browser: true
Console: false
For this you can use isset
<?php
$foo = 'bar';
$bar = null;
switch ($foo) {
default:
case 'bar':
if (isset($bar)) {
echo "true";
die();
} else {
echo "false";
die();
}
}
This code will echo false.
You could also use a double not operator:
<?php
$foo = 'bar';
$bar = null;
switch ($foo) {
default:
case 'bar':
if (!!$bar) {
echo "true";
die();
} else {
echo "false";
die();
}
}
The problem with your default case
In the code you provided (and the code I re-quoted), you will be hitting case 'bar' every time, no matter what $foo is set to.
<?php
$foo = 'notbar';
$bar = null;
switch ($foo) {
default:
case 'bar':
if (!!$bar) {
echo "true";
die();
} else {
echo "false";
die();
}
}
This code will still echo false.
What you should do is include a break in the default case.
<?php
$foo = 'notbar';
$bar = null;
switch ($foo) {
default:
echo "default";
break;
case 'bar':
if (!!$bar) {
echo "true";
die();
} else {
echo "false";
die();
}
break;
}
This code will echo default and nothing else.

Use php ifelse statement as $variable

For example if statement
if($number == 1){
echo '$number == 1';
}
Such statement need to call multiple times. And possibly latter the statement need to change.
Can place this code in external file and the use include.
But better would be create variable something like
$variable = if($number == 1){
echo '$number == 1';
}
This does not work. Tried with ( ), " ". No success.
Any ideas? Is it possible at all?
Updated question
Writing one more time for those who write that question is not understandable.
So need this code if($number == 1){ echo '$number == 1'; } (actually code is much longer) to repeat some 30 times.
And time after time some part of code manually would need to change.
One way how can I do it is to place the code in external file, for example external_file.php and then use require($_SERVER['DOCUMENT_ROOT'] . "/external_file.php");.
Instead of including external content would want to define/create (now I see that need function).
Hope now is clear what I want.
Thanks for answers, will experiment.
Please use functions for reusability
function reuseFun($num){
if($num == 1){
return 'Number = 1';
}
else{
return 'Number != 1';
}
}
echo reuseFun(1);
Maybe like this?
function checkNumber($number) {
if($number == 1){
return true;
}
}
And then you can use it like this:
if (checkNumber(1)) {
echo 'something';
}
Use function :
function myTest($number) {
if($number == 1){
echo '$number == 1';
}
}
That won't work, but you could try this:
if($number == 1) {
$variable = 'number is 1';
} elseif($number == 2) {
$variable = 'number is 2';
}
echo $variable;
It is not clear what you need with the if statement, however if you need shorthand form of if use following code.
echo 'text '. ($number == 1 ? '$number == 1' : 'something else'). ' text';
more examples
if you need to reuse the code just put this code inside the function as follows,
function print_number($number){
echo 'text '. ($number == 1 ? '$number == 1' : 'something else'). ' text';
}

php use switch without break;

whats wrong with my switch ?
Now result:
< more
> less
= equality
!= no't equality
As it should be:
< more
= equality
<?php
$page = 99;
switch ($page)
{
case $page < 121:
echo '< more <br/>';
case $page > 123:
echo '> less <br/>';
case $page == 99:
echo '= equality <br/>';
case $page != 99:
echo '!= no\'t equality <br/>';
}
?>
In your switch statement you're comparing a number with boolean values.
Let's take the first case $page < 121 is true, so the comparison taking place is 99==true which is true according to http://docs.php.net/language.types.type-juggling (switch performs a loose comparison, not a strict like ===). Thus the first case block is executed.
And since you don't have a break statement it falls through to the next case block and the next and so on...
Meaning: This won't work as intended regardless of whether you use break or not.
You don't seem to understand how switch works. What you want is a series of if statements, i.e.
if ($page < 121)
echo '< more <br/>';
if ($page > 123)
echo '> less <br/>';
if ($page == 99)
echo '= equality <br/>';
if ($page != 99)
echo '!= no\'t equality <br/>';
Switch is to be used only when you want to compare a variable against a set of values.
switch ($variable)
{
case "me":
echo "variable is me";
break;
case "you":
echo "variable is you";
break;
default:
echo "Variable is neither of us";
}
The above switch case block can be written as shown below:
if ($variable=="me")
{
echo "variable is me";
}
elseif ($variable=="you")
{
echo "variable is you";
}
else
{
echo "variable is neither of us";
}
DO NOT put an expression near the case statement.
switch ($somethng)
{
case $something < 10:
break;
case $something > 20:
break;
}
Switch is meant to be used only for comparing a variable against a set of values. ONLY! For everything else use a if...elseif..else statement.
The block above is wrong usage. Sometimes more than one of those expressions could be true.
$var = "cat";
switch($var)
{
case "cat":
echo 'My '.$var.' is called Bob.';
break;
case "dog":
echo 'My '.$var.' is called James.';
break;
default:
echo "I don't have an animal";
break;
}
In a switch statemant you compare $var against value in a case. If there is a match, the actual case will be executed, otherwise the default will be executed. You can't use <>!=... in a case, only values like: 1, '1', 'dog', $var2, and so on.
If you want to run the same command for two case you can do:
$var = "cat";
switch($var)
{
case "cat":
case "dog":
echo 'My '.$var.' is called James.';
break;
default:
echo "I don't have an animal";
break;
}
In your code, your forgot to put break; at the end of each case, that's why you see 'everything' in your output. And you miss default: too.
For the task you're doing, i suggest you to use if statements.
if iam not wrong you can't use this characters < > raw in html. use instead the entities > and <.
if you run the script in the command line i got following output.
<?php
ob_start();
$page = 99;
switch ($page)
{
case $page < 121:
echo '< more <br/>';
case $page > 123:
echo '> less <br/>';
case $page == 99:
echo '= equality <br/>';
case $page != 99:
echo '!= no\'t equality <br/>';
}
$buffer = ob_get_clean();
echo str_replace('<br/>', "\n", $buffer);
output
< more
> less
= equality
!= no't equality
which seems to be the correct behavoir.
It is important to understand how the
switch statement is executed in order
to avoid mistakes. The switch
statement executes line by line
(actually, statement by statement). In
the beginning, no code is executed.
Only when a case statement is found
with a value that matches the value of
the switch expression does PHP begin
to execute the statements. PHP
continues to execute the statements
until the end of the switch block, or
the first time it sees a break
statement.
http://de.php.net/manual/de/control-structures.switch.php
';
break;
case $page > 123:
echo '> less ';
break;
case $page == 99:
echo '= equality ';
break;
case $page != 99:
echo '!= no\'t equality ';
break;
default: echo 'Default';
}
?>

Categories