Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is it possible to do something like this:
if ($boolean == true) {
foreach ($variables as $variable) {
}
// some code that can be run either with a loop or without
if ($boolean == true) {
} // end the foreach loop
}
Or is there another way to do this without rewriting the same code twice just to satisfy all possibilities?
The conventional way is to always use a loop. If there is only one item, then you can still loop just once.
Contrived example
$values = …;
if (!is_array($values)) {
$values = array($values);
}
foreach ($values as $value) {
// Do your work
}
I'm not sure if I understand exactly what you're asking, but if you want to run a loop at least once, and continue looping for a condition then "Do While" is your answer. A do while works just like a while, but checks AFTER the first loop is run - meaning it always runs at least once.
PHP Docs for Do While
Do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning.
Example:
$arrayofstuff = array('one ','two ','three '); // Optional array of stuff
$i=0; // Counts the loops
echo 'starting...';
do {
// Do stuff at least once here
// Array stuff if needed
if(isset($arrayofstuff[$i])) {
echo $arrayofstuff[$i]; // Uses loop # to get from array
} else {
break; // ends loop because array is empty
}
$i++;
} while (true);
For what it's worth, forcing a variable into a single value array would probably be easier to read. As you can see there's a lot going on here for such a simple task.
(Dionne Warwick voice) That's what functions are for:
function doSomething() {
//whatever
};
if ($boolean)
for($variables as $variable) doSomething();
else
doSomething();
That kind of syntax you thought about isn't valid in PHP. It's a very clever idea though. But code maintenance of one of there would bring hell on earth. Better forget it.
why not just plain:
if($boolean){
foreach($a as $b){
// do stuff
}
}else{
// do other stuff
}
What you want would be done like so...
foreach ($variables as $variable) {
// some code that can be run either with a loop or without
if ($boolean !== true) {
break;
}
}
But this is not as readable as just using an if/else statement
Related
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 6 years ago.
Improve this question
Code 1 :
if( !(varOfsomeClass->isValid($imParams)) ){
//some function i need to run
}
run function isValid
reverse value with not (!)
check value with if
Code 2 :
if( (varOfsomeClass->isValid($imParams)) ){
} else {
//some function i need to run
}
run function isValid
check value with if
enter else part(maybe, or do nothing because isValid is true)
which is more efficient? which is better to use?
nb: Code 1 is indeed more 'human'
if( !(varOfsomeClass->isValid($imParams)) ){
//some function i need to run
}
This type code use Less resource when comparing with code 2 type.
Well, I would say example #1 is more efficient, but I doubt this type of micro-optimization will give you performance gains even measurable in micro seconds, so it's not worth it.
Remember, the if() itself evaluates the expression passed to it for truthly/false values, so adding ! is only redundant in most cases.
In other words, why would you need to do:
$number = 1;
if(!$number){}
instead of this.
$number = 1;
if($number){}
unless you are trying to quickly output something if $number is false, then move on to something else, it does not make any sense to use the first one.
It looks like you are not doing anything in the case isValid returns true. I would recommend to stick with the first version, where you only have a single if statement, for multiple reasons:
Less code to read, easier to understand
Leaving an empty block can be interpreted as "code not finished" for other contributors
Technically speaking, except a JUMP assembly instruction saved maybe (depending on the interpreter), both code will be as efficient... Do not try to think about those micro-optimization if it makes the code less readable.
An interesting question.
I would suggest to put it in this mini test suite and test it out:
$startA = microtime(true);
for($i = 0; $i < 10000; $i++)
{
//Code 1
}
$endA = microtime(true);
unset ($all, $your, $variables);
$startB = microtime(true);
for($i = 0; $i < 10000; $i++)
{
//Code 2
}
$endB = microtime(true);
echo $endA-$startA."<br />";
echo $endB-$startB."<br />";
They are both equaly effective.
The first on needs an additional ! negate statement, the second on has an additional else statement. The C code php uses is very effective when handling if/else constructs. It might even be the case that the second statement will get reduced to something similar like the first function in the ast parser.
However the second one is less readable an I would prefere the first one.
The best using if is depend on how you need your return value,
If you need return value not condition (reverse / false) only, u could use :
if ( ! varOfsomeClass->isValid( $imParams ) ){
//some function you need to run
}
If you need the right (true) return value, then use :
if ( varOfsomeClass->isValid( $imParams ) ){
// some function you need to run true
}
If you need true and false (both) return value, then use :
if ( varOfsomeClass->isValid( $imParams ) ){
// some function you need to run true
} else {
// some function you need to run false
}
And for your note, don't ever use this :
if ( varOfsomeClass->isValid( $imParams ) ){
} else {
//some function you need to run
}
That's what you called not 'human', it's like you are light but u are doing dark. :)
This question already has answers here:
What's the difference between if and elseif?
(8 answers)
Closed 6 years ago.
I have the following functions:
if(A==B)
{
//do stuff
}
if(C==B)
{
//do stuff
}
if(A==B)
{
//do stuff
}
else if(C==B)
{
//do stuff
}
What is the difference between these two? I get the meaning of it but I have seen programmers prefer the first one instead of the 2nd one? why?
I personally prefer the 2nd one.
That's mostly a question of preference. I saw many programmers using both cases regardless of the actual function.
But correctly use the first case if you want both conditions to be chekced absolutely, the second one as a nested condition.
In the first case, both will be executed which makes it slower than the second one, as it checks only for the elseif, if the if condition is false
$var = 1;
if($var+1 ==2)
{
echo "test1";
}
if($var-0==1)
{
echo "test2";
}
if($var+1==2)
{
echo "test1";
}
else if($var-0==1)
{
echo "test2";
}
will output
test1test2test1
so we see, that number 2 ignores the elseif, which makes it faster.
In the first condition both the statements are excecuted because they are independent to each other, so all of them will be tested.
if(A==B)
{
//do stuff
}
if(C==B)
{
//do stuff
}
In second else if is just a nested if inside an else, so only one will of them will be tested, either if or elseif
if(A==B)
{
//do stuff
}
else if(C==B)
{
//do stuff
}
Not the same.
else if (C==B) will not be executed (even if C equals B) if the first condition was true.
without "else", just if (C==B) will be executed even if the first condition was true (in that case A==C :)
If only one variable is equal and need to run the same code regardless, it is better to use the first code so there is no loss of performance. But if you need to run different code depending on your variable, then the second is better.
if i'm looping over an array, and while in the middle of one of the loops i discover some small issue, change ...something..., and need to try again ... is there a way to jump back to the top of the loop without grabbing the next value out of the array?
i doubt this exists, but it would be some keyword like continue or break. in fact, it would be a lot like continue, except that it doesn't get the next item, it maintains what it has in memory.
if nothing exists, can i insert something into the array in such a way that it will become the next key/value in the loop?
maybe this would be easier with a while(array_shift())...
or i suppose a recursive function inside the loop might work.
well, my question is evolving as i type this, so please review this pseudo code:
foreach($storage_locations as $storage_location) {
switch($storage_location){
case 'cookie':
if(headers_sent()) {
// cannot store in cookie, failover to session
// what can i do here to run the code in the next case?
// append 'session' to $storage_locations?
// that would make it run, but other items in the array would run first... how can i get it next?
} else {
set_cookie();
return;
}
break;
case 'session':
set_session();
return;
break;
}
}
i'm sure there is no keyword to change the value tested against in the switch mid-stream... so how should i refactor this code to get my failover?
Not with a foreach, but with more manual array iteration:
while (list($key, $value) = each($array)) {
if (...) {
reset($array); // start again
}
}
http://php.net/each
http://php.net/reset
It seems like a simple fall through would do the trick though:
switch ($storage_location) {
case 'cookie':
if (!headers_sent()) {
set_cookie();
break;
}
// falls through to next case
case 'session':
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What I am doing wrong with the following code? I want to compare if the element $my_id is present within the array $arr. If it is present return TRUE else return FALSE.
for($i=0;$i<$cnt;$i++)
{
if($arr[$i] == $my_id)
{
return TRUE;
}
else
{
return FALSE;
}
}
You could replace that with...
return in_array($my_id, $arr);
...assuming you don't really want to return FALSE if the first element does not match.
If that is actually what you wanted, you could use...
return $arr[0] == $my_id;
If you want to leave your code mostly intact, just move the return FALSE to outside of the loop body.
The issue you are having is that you aren't looping entirely through the array. You are returning true/false after the first item in the array, irrespective of subsequent array entries after [0]
Well, I believe you should remove the else statement, unless you always just have one element in the array. I mean -- from the example you're showing, you're exiting the loop with this. I doubt this is what you want.
If you just need to know, if a value is within a given array
in_array($value, $array);
Maybe you want get the index of (the first occurence of) the value too
$index = array_search($value, $array);
if ($index === false) {
// Not in array
} else {
echo $array[$index];
}
The error in Your code is to return false on $arr[$i] != $my_id. The algorithm should look something like this:
for($i=0;$i<$cnt;$i++)
{
if($arr[$i] == $my_id)
{
return TRUE;
}
}
return FALSE;
P.S. This isn't the best solution for this problem in PHP language. You should use one from alex.
I am getting the key from a given value in a multidimensional array. It works fine except that I cannot seem to access the variable from OUTSIDE the nested foreach loop that I'm using to get the key.
so my foreach loop is: ($name_books is the multi-d array which contains 3 smaller arrays)
foreach($name_books as $test) {
foreach ($test as $key => $value) {
$book_code = array_search($row['name'],$test);
echo $book_code; //just to see if it works, which it does
break;
}
}
//But then if I go outside of the loop..
echo $book_code." is the book code"; // <--DOES NOT WORK
So I know that I'm dealing with variable scope issues here and I've tried declaring globals inside the foreach loop but nothing works.
I'm sure there is something absurdly simple I'm missing!
EDIT:
urg..I took a step back and realized something else,
all this is happening inside a while loop (getting stuff from a db)
so the code is more like:
while($row=mysql_fetch_assoc($result)) {
...original foreach loop from above
}
apologies for not including this, I was focusing on this tiny piece and forgot to back up and see where it fit.
break;
Will only exit the internal nested foreach. If there are more rows in $name_books, it will continue looping and eventually overwriting $book_code with 'false' values from array_search;
Once you've found the value you're looking for, use:
break 2;
Regarding your edit, where you break depends on what you're doing with the value you've found for $book_code. If you don't plan on continuing, change the parameter for break. break 3; will exit the while loop too. Change the value depending on the level of nesting.
This has nothing to do with variable scope so long as what you posted is exactly what you have in your script.
I think what the problem is, is that you are only breaking out of the inner loop. In each iteration of the outer loop, $book_code will get changed, so you need to stop the outer loop as well. Try changing break; to break 2; and see if it fixes your problem. That causes it to break out of both the inner and the outer loop.
Edit: I think you can also simplify your code:
foreach ($name_books as $test) {
$book_code = array_search($row['name'], $test);
if ($book_code !== FALSE) {
break;
}
}If I knew more about your structure, this could possibly be reduced down to a single SQL statement and 0 loops.
simshaun is right, but I would actually take a different approach.
I would check for the existence of $book_code in my foreach loops rather than dealing with the breaks.
New Code
foreach($name_books as $test) {
foreach ($test as $key => $value) {
if(!isset($book_code)){
$book_code = array_search($row['name'],$test);
echo $book_code; //just to see if it works, which it does
}
}
}
echo $book_code." is the book code";