php continue - alternative way? - php

I just started learning php and I have to do something like this which I got it working but I just have a few questions I want to ask for alternate way of doing but eh first of all the br/ is suppose to be with <> but somehow if i do that the coding at the bottom will see it as a line break.
Anyways if questions are...
With the coding below the outcome will be 0-9 (without 5) but I have to set $zero=-1 if I put $zero=0 then the outcome would be 1-9 (without 5) is there a way I don't have to make $zero=-1 and still have the outcome of 0-9 (without 5)?
I realized I have to put $zero++ before the if and continue statement if I put it at the end of the script after echo "$zero" . "br/"; the script won't run as wanted. Is this how it is suppose to be or I just don't know the other way of doing it.
Thanks in advance for people replying ^_^
$squared = pow(3,2);
echo "\"3 squared is $squared:";
echo "br/";
$zero = -1;
while ($squared > $zero)
{
$zero++;
if ($zero == 5)
{
continue;
}
else if ($squared == $zero)
{
echo "$squared\"";
}
else
{
echo "$zero" . "br/";
}
}

Here it is (you were almost there :P )
$nr = 0;
while ($squared > $nr) {
if (5 == $nr) {
$nr++; // add this
continue;
} else if ($squared == $nr) {
echo "$squared\"";
} else {
echo "$nr" . "<br/>";
}
$nr++; // move to the bottom
}
PS: You're welcome #clement

Change your while loop to while ($squared >= $zero) and then set $zero = 0;
Should work!

Related

How to select the next number in a loop?

The function for the primes is clear, so I omitted it.
$a=10;
$z=30;
for($prime = $a; $prime<$z; $prime++)
{ if
(Prim($prime) == TRUE)
{ echo $prime."<br/>";}}
Now I want to select the next term of the sequence as well, in order to perform an operation between the variable $prime and $next_prime, as long as the loop goes on - like for example:
$prime_gap=bcsub($next_prime, $prime);
Whatever solutions I find and I try, it's never the proper one. It's surely very simple but I am already desperate.
I would suggest you start by creating a next_prime() function. Like this, for example:
function next_prime($n) {
do {
$n++;
} while (!Prim($n));
return $n;
}
Then you can refactor your code quite easily:
$a=10;
$z=30;
for ($p1=next_prime($a),$p2=next_prime($p1); $p2<$z; $p1=$p2,$p2=next_prime($p2)) {
if (some_function($p1, $p2)) {
echo "I like $p1 and $p2\n";
}
}
The if I add in the for loop is not so nice, but if you want something simple and easy to understand, you can still use it (I switch the name from $prime & $next_prime to $prime & $previous_prime, I think it makes more sense)
$a=10;
$z=30;
$previous_prime = 0;
for($prime = $a; $prime<$z; $prime++)
{
if (Prim($prime) == TRUE)
{
echo $prime."<br/>";
if ($previous_prime == 0) {
$previous_prime = $prime
} else
{
$prime_gap = $prime - $previous_prime;
$previous_prime = $prime;
}
}
}

using for loop and if in php

I have loop using for which results in some values:
$value1, $value2, $value3, $value4, ...
How can I make a calculation or relation between these values?
For example, if any two values < 40 echo something?
I hope that some code will make the idea clear:
<?php
$value=$_POST['name'];
for($i=1;$i<=$value;$i++)
{
$value{$i}=$_POST['name{$i}'];
}
if($value{$i} < 40)
{
echo "you failed";
}
else
{
echo "you succeeded";
}
?>
I want to show the message "you failed" if two values are < 40.
How can I do that?
I'm struggling to make sense of what your current code is actually doing, but that could just be that my PHP is a bit rusty. Either way, it sounds like the general pattern of what you're trying to do is to keep a count of fails and successes. As an overall structure (that is, not to be copied/pasted as-is since I don't know what your $value actually is here), it might look something like this:
$fails = 0;
$successes = 0;
for ($i = 0; $i < len($values); $i++)
{
if ($values[$i] < 40)
{
$fails++;
}
else
{
$successes++;
}
}
At this point $fails contains the count of values less than 40 and $successes contains the count of values greater than 40. Then you invoke your business logic for determining the overall result:
if ($fails >= 2)
{
echo "you failed";
}
else
{
echo "you succeeded";
}
To answer your question you can use the foreach statement
$value=$_POST['name'];
$hasValue = 0;
foreach($value as $key => $dat){ // since we have the value from $_POST we use foreach statement to loop it
if($dat < 40){ // check if the data in the list is less than 40
$hasValue++; // increment it if is.
}
}
echo ($hasValue > 2)?#"You failed":#"Success"; // check if it has more than 2 less than 40 values.
something like the above
and try to read about PHP
btw haven't code much in php lately so apologies for some syntax
As soon as any two values add to less than 40, the "failed" message shows and the loops are exited. If not, the success message shows.
$x = false;
foreach ($value as $k1 => $v1) {
foreach ($value as $k2 => $v2) {
if (($v1 + $v2) < 40 && ($k1 != $k2)) {
echo "you failed";
$x = true;
break (2);
}
}
}
if (!$x) echo "you succeeded";

PHP continue if conditions are ok

Is there something in php that can halt or let the script proceed if things are ok?
In my current scripts I do like this (for this example):
$fetch = false;
if($i == 10){
echo 'I is clear'
$fetch = true;
}
if($fetch){
//Do database work here
}
echo 'This should be seen no matter what the above';
Instead of the $fetch in there, can I do something else? I don't want to stop the entire script after that like what die() or exit does.
Here's an example that should help you:
<?php
function doLoop() {
for($i=0;$i<100;$i++) {
if($i != 50) {
continue; //It's not 50, skip it
}
//Otherwise
printf("Loop: $i");
}
}
function doBreak() {
for($i=0;$i<100;$i++) {
if($i != 49) {
continue; //It's not 49 yet, continue
} //Otherwise, break
printf("Loop: $i");
break;
}
}
doLoop();
doBreak();
?>
break; can be used to end a loop when a condition is met, while continue; can also be used to skip a certain value if a condition is not met. Using die(); would stop your whole script from executing, preventing it to call anything that comes after the die(); statement because that's how the execution of the scripts pretty much go, from the top to the end.

How do I clean up this if/else statement? (refactoring)

I know there must be a nicer way to do this, but whenever I search "&&" i don't get good enough results...
<?php
if (empty($row[ContactName]) && empty($row[ContactEmail]) && empty($row[ContactPhone]) && empty($row[Website])){
echo "Not Provided";
}
else{
...do stuff...
}
?>
Thanks!
What is wrong with the original code?
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
Looks like fine code to me...
<?php
$i=1;
$ar=array('ContactName','ContactEmail','ContactPhone','Website')
foreach($ar as $a)
if (empty($row[$a]))
{
$i=0;
break; //to make code fast
}
if($i) //do stuff
else echo 'not provided';
?>
or if you really want to make your code extra small then change your column name in database
From To
ContactName Col1
ContactEmail Col2
ContactPhone Col3
Website Col4
and then do
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
else echo 'Not Provided';
?>
However it is not good to rename column as it will make your db somewhat less understandable.
As php functions have a lot of inconsistency, It's always a good idea using a library to make it more consistent.
put this function in that library:
function empty()
{
foreach(func_get_args() as $arg) if (empty($arg)) return false;
return true;
}
usage:
if (empty($row[ContactName], $row[ContactEmail], $row[ContactPhone], $row[Website])) {
echo "Not Provided";
}
you could make it as short as this if compactness was more important than readability :)
$required = array('ContactName', 'ContactEmail', 'ContactPhone', 'Website');
$ra = array_filter(array_intersect_key($row,array_flip($required)));
if(empty($ra)){
echo "Not Provided";
}
else{
//....
}
you can't put array_filter inside empty() or you get "Fatal error: Can't use function return value in write context"
1) array flip is turning your $required values into keys
2) array_intersect_key throws away any $row keys not found in $required
3) array_filter throws away any empty values
leaving you with a zero length array, which is empty. No need to worry about array lengths or loops
<?php
$flag = 1;
if (empty($row[ContactName])){
$flag = 0;
}
if (empty($row[ContactEmail])){
$flag = 0;
}
if (empty($row[ContactPhone])){
$flag = 0;
}
if (empty($row[Website])){
$flag = 0;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
?>
OR
$flag = 1;
$i=0;
$mustarray = array('ContactName','ContactName','ContactName','ContactName'); //or any number of fields that you want as mandatory
foreach($yourresult as $row){
if(empty($row[$mustarray [$i]])){
$flag = 0;
}
$i++;
}
if($flag == 0){
echo "Not Provided";
}else{
//do stuff
}
Do not play with making arrays and stuff just to make code look nicer.
As Tommy pointed
<?php
if (empty($row[ContactName])
&& empty($row[ContactEmail])
&& empty($row[ContactPhone])
&& empty($row[Website]))
{
echo "Not Provided";
}
else{
...do stuff...
}
?>
this code is nice, just need proper formatting like he pointed.
Making arrays and then launching loop will decrease performance
<?php
$i=1;
for($a=1;$a<5;$a++)
if (empty($row['Col'.$a]))
{
$i=0;
break;
}
if($i)//do stuff
?>
this might look small, nice and "pro", but has more operations to give same results as a simple if instruction.
Not saying that it cant be done faster, i don't know php well, just remember about code executing speed.

stop script or loop after first match without using exit;

no idea how to ask this question... the problem is that I need to stop the loop from runing if if ($current[$id][$i]['item'] == '') is true, so whatever the script needs to do or in this case echo, don't get repeated 15 times.
If using exit; the whole page will stop to render, so, any ideas ?
Thanks in advance.
If the question is not clear enough don't hesitate to ask using the comments, I will more than happy to clarify any doubts.
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
//do something
}
$a++;
}
use break
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
break;
}
$i++; //<- that should probably be $i instead of $a?
}
How about using the break control structure?
You need to break. Also, your current loop is endless and will therefore time-out. Presumably you meant to increment $i, not $a.
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
break; //<-- terminate loop
}
$a++; //<-- shouldn't this be $i++?
}
There is only 2 ways to break a loop... using exit; and break;....
break; is what you want it will exit the loop and continue execution, exit will end the script.
$i=1;
while($i<=15) {
if ($current[$id][$i]['item'] == '') {
echo 'Done!.';
break; // or you can make value of $i = 20;
}
$a++;
}

Categories