What should be passed into if() to print 'Hello World'? - php

What should be passed into the if() to print the output as "Hello World"? [Note: It should execute the else block.]
if(?){
} else {
echo "World";
}

I needs to evaluate to false, and print "Hello" at the same time. printf returns the length of outputted string upon success which is evaluated to true when read in a Boolean context. So reversing that will evaluate to false, executing the else block.
if(!printf("Hello ")){
} else {
echo "World";
}

!printf("Hello ")
By default, printf in 'C' returns true.

if(!printf("Hello "))
{}
else
{
echo "World";
}
You can do in this way...

There is also an alternate solution for this question:
class test{
function __construct()
{
echo "Hello";
}
}
if(!new test){
}else{
echo "World";
}

Anything that evaluates to FALSE.

if understands logical result, i mean TRUE-FALSE
so any any condition that results in true/false results matters for if so you can use
if(true){
echo 'this is executed';
}else{
echo "world";
}
OR
if(false){
echo 'this is executed';
}else{
echo "world";
}
i hope this works

if(printf("Hello ")) {
}
else{
echo "World";}
i think this is enough.....sorry if not

Related

Checking for undefined variables in a function php

So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";

Does testing for a false statement execute the same statement if TRUE

The code block below actually executes when the whole script is run. What is not clear to me is that method write only test for the case of if data is not written to file. then the Exception should be thrown. It does say that if $data exist and writeable then write to it.
public function write($data) {
if (#!fwrite($this->_fp, $data . "\n")) {
throw new Exception('Could not write to the file.');
}
}
What am used to is this :
if( condition is true ) {
echo 'Run Code';
} else {
echo 'Throw Exception';
}
or something like this
public function query($sql) {
$result = mysql_query($sql, $this->connection);
if(!$result){
die("Database Query Failed : ". mysql_error());
}
return $result;
}
How is this possible ?
as mentioned in here if(expr) evaluates the expr to its Boolean value.. which means that in your example when calling the write function, the fwrite function always gets executed and then if checkes if it returns a falsy or truthy value..
and from the doc fwrite() returns the number of bytes written, or FALSE on error. hence #!fwrite($this->_fp, $data . "\n") evaluates to true on error, and the exception is thrown
I'm not good at explaining such kind of things, but let's try :)
I think you misunderstood how a condition works.
Let's use a simple example
if($x == 1) {
echo 'Run Code';
} else {
echo 'Throw Exception';
}
The if and what you put inside are independant. A condition is just a statement that returns a boolean, and a if just tests a boolean (whatever returned it). So you could transform this example like this :
$is_x_equal_to_one = ($x == 1); // $is_x_equal_to_one now contains true or false
if($is_x_equal_to_one) {
echo 'Run Code';
} else {
echo 'Throw Exception';
}
The ! operator negates an expression. If it's true, it will return false, and if it's false, it will return true.
So you could revert your condition like this :
$is_x_equal_to_one = ($x == 1);
if(!$is_x_equal_to_one) {
echo 'Throw Exception';
} else {
echo 'Run Code';
}
Now what if you don't need to run any code and you just want to say that "something is broken" if $x is not equal to 1 ? The else statement is always optional :
$is_x_equal_to_one = ($x == 1);
if(!$is_x_equal_to_one) {
echo 'Throw Exception';
}
fwrite not only writes to a file, it also returns false if it didn't worked. If it works, it returns a positive integer. And positive integers are evaluated as true with PHP.
That means you can use it like that :
$is_write_successful = fwrite($this->_fp, $data . "\n");
if(!$is_write_successful) {
echo 'Throw Exception';
}
And finally, you can shorten this code by removing a useless temporary variable :
if(!fwrite($this->_fp, $data . "\n")) {
echo 'Throw Exception';
}
You can rewrite the if as this:
$returnValue = #fwrite($this->_fp, $data . "\n");
if (!$returnValue) {
So it will always execute the fwrite function.

Variable set to false

I wrote this REALLY simple code:
$foo=false;
echo $foo;//It outputs nothing
Why? Shouldn't it output false? What can I do to make that work?
false evaluates to an empty string when printing to the page.
Use
echo $foo ? "true" : "false";
The string "false" is not equal to false. When you convert false to a string, you get an empty string.
What you have is implicitly doing this: echo (string) $foo;
If you want to see a "true" or "false" string when you echo for tests etc you could always use a simple function like this:
// Boolean to string function
function booleanToString($bool){
if (is_bool($bool) === true) {
if($bool == true){
return "true";
} else {
return "false";
}
} else {
return NULL;
}
}
Then to use it:
// Setup some boolean variables
$Var_Bool_01 = true;
$Var_Bool_02 = false;
// Echo the results using the function
echo "Boolean 01 = " . booleanToString($Var_Bool_01) . "<br />"; // true
echo "Boolean 02 = " . booleanToString($Var_Bool_02) . "<br />"; // false

How to display a return value on the browser?

I have the following inside a function something():
if ($cod == 1000)
{
$message = 'Some Message';
return $message;
}
Later, I call this function:
try
{
$comandoController->someThing();
}
I was expecting to see "Some Message" on the browser. But I don't.
Note: If I echo something like echo "hello" inside the conditional, I can see it. So the condition is the case.
Instead of $comandoController->someThing(); should we do the following:
$result = $comandoController->someThing();
echo $result;
Works as designed. This
try
{
$comandoController->someThing();
}
will not output anything to the browser. The return value can be echoed:
echo $comandoController->someThing();
or stored:
$value = $comandoController->someThing();
but as it stands, no browser output will take place.
You need to echo that:
echo $comandoController->someThing();
Or use the echo inside your function instead:
if ($cod == 1000)
{
echo 'Some Message';
}
Now you simply need to do:
$comandoController->someThing();

How to do an if statement on a function in PHP?

I just realized that you can't just use an if statement on a function, for example this doesn't work:
function sayHello()
{
echo "Hello World";
}
if(sayHello())
echo "Function Worked";
else
echo "Function Failed";
I also saw that a function can't be put as the value of a variable. So how can I do an if statement to check if a function has executed properly and display it to the browser?
It's not working since sayHello() doesn't return anything place return true in there or something.
if (sayHello() === FALSE)
echo "Function Failed";
else
echo "Function Worked";
this will work
<?php
$name1 = "bobi";
function hello($name) {
if($name == "bobi"){
echo "Hello Bob";
} else {
echo "Morning";
}
}
hello($name1);
?>
function selam($isim)
{
if ($isim == 'ugur') {
return 'Selam '.$isim.' :)';
}
return 'Sen kimsin kardes?';
}
echo selam('ugur');

Categories