Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have the following code and want to know if there is a better way to use the if-else with same result other than using the same else three times?
if($condition1) {
// some code to get condition 2
if($condition2) {
// some code to get condition 3
if($condition3) {
$dt = $something;
} else {
$dt = "";
}
} else {
$dt = "";
}
} else {
$dt = "";
}
You could easily get rid of some of the extra else statements.
$dt = ""; // Assign $dt in the beginning
if ($condition1) {
// some code to get condition 2
if ($condition2 && $condition3) {
// some code to get condition 3
$dt = $something;
}
}
Two ways to avoid nested statements.
using a function
$dt = doSomething($params);
function someFunction ($params) {
if (!$condition1) {
return "";
}
// do stuff for condition 1
if (!$condition2) {
return "";
}
// do stuff for condition 2
if (!$condition3) {
return "";
}
return $something;
}
using a do/while statement
do {
$dt = "";
if (!$condition1) {
break;
}
// do stuff for condition 1
if (!$condition2) {
break;
}
// do stuff for condition 2
if (!$condition3) {
break;
}
$dt = $something;
} while (0); // since this will evaluate to false it will not loop at all.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
So my taslk is to program two numbers randomly (for example 0 and 1) and then replace the numbers with "Hello" and "bye". I've done the generating it rendomly part, but now I'm struggling with the replacing Part. It would be cool If the solution would be by using "if" and "else"
Here's what i've done so far,
thank you in advance
<?php
$zaehler = 0;
while($zaehler < 10)
{
echo mt_rand(0, 1);
if(0)
{
echo "bye" ;
}
else (1) ;
{
echo "hello" ;
}
$zaehler++;
}
?>
For your case, just use a comparison statement
e.g.
if($result==0) { // do something;} else {// do another thing; }
(the $result will only be either 0 or 1, so just use one if-then-else)
<?php
$zaehler = 0;
while($zaehler < 10){
$result=mt_rand(0, 1);
echo $result;
if($result==0) {
echo "bye" ;
} else {
echo "hello" ;
}
$zaehler++;
}
?>
So i just saw your post,
First, you need to assign mt_rand to a variable.
Afer your statement IF isnt correct, you need to evaluate something like this $i === 0
And about your else you need an else if, so you can take a look to this code ;)
$idx = 0;
while ($idx < 10) {
$random_int = mt_rand(0, 1);
if ($random_int === 0) {
echo "bye\r\n";
} else if ($random_int === 1) {
echo "hello\r\n";
}
$idx++;
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need to make a conditional statement where the 5 variables should be empty before perform an action. The problem is some variables can be zero, false or NULL value. How to catch all of them?
Which one is better?
If (!$a && !$b && !$c && !$d && !$e) {
// do some action
} else {
exit;
}
OR
If (empty($a) && empty($b) && empty($c) && empty($d) && empty($e)) {
// do some action
} else {
exit;
}
Thank you.
First of all, use "code sample" to show code.
When you use !$a you are actually casting $a to boolean.
The problem here is
$a = 0;
if (!$a) {
echo 'NOT EMPTY';
} else {
echo 'EMPTY';
}
//OUTPUT EMPTY BECAUSE 0 to boolean is FALSE
Same example with NULL value.
About empty i advice you to check the documentation
Read it and choose the way that fit your needs.
Hope this helps
This could be an approach to check multiple variables are empty at once.
<?php
$a = $b = $c = $d = $e = '';
#$b = 5; // comment out to go on else block
if (empty($a . $b . $c . $d . $e)){
echo "All variables are empty, do what you want to do man";
}else{
echo "One of variable is not empty";
}
?>
This question already has answers here:
The 3 different equals
(5 answers)
Closed 5 years ago.
why the IF(the lastest one with else if and else) is doing all the time only first condition and only the first part ($filtry_1value[$key] = 'min_cena'), even if the condition shouldnt be true. I have another solution (less dynamic), if I will not fix this one, but I would like to know, why it is not working... I think it will be a trivial thing, but I cannot see it.
PS: I am working with laravel.
$filtry_1value = ['stat', 'lokalita', 'patro', 'min_cena', 'max_cena', 'min_uzitna_plocha', 'max_uzitna_plocha'];
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] = 'min_cena' OR $filtry_1value[$key] = 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] = 'max_cena' OR $filtry_1value[$key] = 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
may be-
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
You need to use the double equal sign for comparisons. == not a single =
Your if's should look like:-
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
// ...
} elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
// ...
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new at php and I am not sure what I am doing wrong. I am trying to list all the records from a txt file. However, my code is only displaying the first line. How can I get the code to display all the records from the file?
$count = 0;
$soldOut = 0;
$eventFile = fopen("performances.txt", "r");
$event = fgets($eventFile);
while ( feof($eventFile));
{
list ($dateEvent, $performer, $ticketprice, $status) = explode(":", $event);
if($status == "Yes")
{
$status = "Tickets are still available";
$count = $status +1;
}
else
{
$status = "***SOLD OUT***";
$soldOut = $status +1;
}
print("<tr><td>$dateEvent </td>");
print("<td>$performer </td>");
print("<td>$ticketprice </td>");
print("<td>$status</td></tr>");
$event = fgets($eventFile);
}
Pay attention to the docs, you'll notice that your loop should be:
while( !feof($eventFile)) {
$event = fgets($eventFile); // THIS is where you get the current line
// do stuff here
}
you can read file this way. You can find more on this http://us1.php.net/function.file-get-contents
<?php
$data = file_get_contents("performances.txt",FILE_USE_INCLUDE_PATH); //read the file
$convert = explode(":", $data); //create array separate by new line
for ($i=0;$i<count($convert);$i++)
{
echo $convert[$i].', '; //write value by index
}
?>
Looping as instructed at http://www.php.net/manual/en/function.fgets.php
Basically, keep looping until fgets nolonger returns anything, and then check if pointer matches with end of file.
I also suggest you take a look at http://www.php.net/manual/en/function.stream-get-line.php
the comments make a case for performance gains.
$count = $soldOut = 0;
$eventFile = fopen("performances.txt", "r");
if ($eventFile) {
# Keep reading as long as fgets returns content
while ( ($event = fgets($eventFile)) !== false ) {
list ($dateEvent, $performer, $ticketprice, $status) = explode(":", $event);
if($status == "Yes") {
$status = "Tickets are still available";
++$count; # increase count with one
} else {
$status = "***SOLD OUT***";
++$soldOut; # increase soldout with one
}
echo '<tr>',
'<td>',$dateEvent,'</td>',
'<td>',$performer,'</td>',
'<td>',$ticketprice,'</td>',
'<td>',$status,'</td>',
'</tr>';
}
# something went wrong
if (!feof($eventFile)) {
echo "Error: unexpected fgets() fail\n";
}
# remember to close them files
fclose($eventFile);
} else {
# failed to open
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Something I've never been sure about is how many variable checks to do in PHP. For example take the following piece of code. I am not checking any of the variables before I assign them or pass them to a function to see if they contain what I expect
$carId = '12';
$aCar = fetchCar($carId);
$make = $aCar['make'];
$model = $aCar['model'];
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
Now if I add some checks
$carId = '12';
if(is_numeric($carId))
{
$aCar = fetchCar($carId);
if(isset($aCar['make']) && is_string($aCar['make']))
{
$make = $aCar['make'];
}
else
{
//Report error
}
if(isset($aCar['model']) && is_string($aCar['model']))
{
$model = $aCar['model'];
}
else
{
//Report error
}
if(isset($aCar['year']) && is_numeric($aCar['year']))
{
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
}
else
{
//Report error
}
}
else
{
//Report errors
}
The code is now better but is it a bit too excessive and bloated? Should I be doing this many checks?
If I shouldn't be doing this many checks where do you draw the line between what you should and shouldn't check?
This is the dilemma of a dynamic type language.
It depends heavily on what fetchCar() function is doing.
The approach i would take is assume fetchCar is returning a car array or throwing exception.
If you combine this with good exception handling logic you can end up with clean and stable code.
For example:
function fetchCar($id) {
$car = queryDatabaseSomehow();
if (empty($car)) {
throw new ExceptionNotFound();
}
//eventually you can put your type checking here?
if (!isset($car['x']) || !is_string($car['x'])) {
throw new ExceptionDb();
}
}
echo fetchCar(3)['make'];
Also if you would like to do this super-proper and go fully OOP, Car should become a class with make,model and year as its members. fetchCar() would return Car or throw Exception. But this is not always desirable of course.
One issue that some people haven't noticed. Be wary of using is_string:
<?php
$var = "test";
$var['something'] = 2;
if(is_string($var['something'])) {
echo "Hello world!"; // Will echo this because $var is a string!
} else {
echo "Hello hell!";
}
echo "<br/>";
echo $var['something']; // returns 2
?>
PHPFiddle.
Compare it with this:
$var = array('something' => 2);
if(is_string($var['something'])) {
echo "Hello world!"; // $var is now an array
} else if (is_numeric($var['something'])) {
echo "Hello hell!"; // Will echo this because $var is string!
}
echo "<br/>";
echo $var['something'];
You need to check whether $var is an array, as it might give you unexpected results. isset($var['something']) will return true in the first example.
To answer your question, I don't think those are too many checks. It really depends on what fetchCar() does and how it gets the data. If you can't trust it (say, it's based on user data) then you should perform all these checks. If not, then there is no point really.
I rather turn it all into a function that can be reused for these cases.
function check_keys($arr_check, $arr_cond) {
$boo_success = TRUE;
foreach(array_keys($arr_cond) as $h)
if (in_array($arr_cond[$h], array('is_string', 'is_numeric'))) {
if ( ! isset($arr_check[$h]) or ! ($arr_cond[$h]($arr_check[$h]))) {
$boo_success = FALSE;
echo "The key {$h} is missing!";
// If run through a class, $this->errors[] = 'error message';
}
} else {
$boo_success = FALSE;
echo 'Invalid function';
}
return $boo_success;
}
$arr_keys = array('make' => 'is_string',
'model' => 'is_string',
'year' => 'is_numeric');
if (check_keys($aCar, $arr_keys)) {
// Run successful stuff
}