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;
}
}
}
I need to check if some text areas are set, but there might be a lot of them. I want to check if every single one of them is set inside an if statement with a for loop.
if(//for loop here checking isset($_POST['item'.$i]) )
You could do this:
// Assume all set
$allSet = true;
// Check however many you need
for($i=0;$i<10;$i++) {
if (!isset($_POST['item'.$i])) {
$allSet=false; // If anything is not set, flag it and bail out.
break;
}
}
if ($allSet) {
//do stuff
} else {
// do other stuff
}
If you've only a few, or they're not sequential there's no need for a loop. You can just do:
if (isset($_POST['a'], $_POST['d'], $_POST['k']....)) {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
try using this:
$post=$_POST;
foreach($post as $key=>$value){
if (isset($value) && $value !="") {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
You can try:
<?php
$isset = true;
$itemCount = 10;
for($i = 0; $i < $itemCount && $isset; $i++){
$isset = isset($_POST['item'.$i]);
}
if ($isset){
//All the items are set
} else {
//Some items are not set
}
I'm surprised that after three answers, there isn't a correct one. It should be:
$success = true;
for($i = 0; $i < 10; $i++)
{
if (!isset($_POST['item'.$i]))
{
$success = false;
break;
}
}
if ($success)
{
... do something ...
}
Many variation are possible, but you can really break after one positive.
Yes, one may have a loop within an if-condtional. You may use a for-loop or you may find it more convenient to use a foreach-loop, as follows:
<?php
if (isset($_POST) && $_POST != NULL ){
foreach ($_POST as $key => $value) {
// perform validation of each item
}
}
?>
The if conditional basically tests that a form was submitted. It does not prevent an empty form from being submitted, which means that any required data must be checked to verify that the user provided the information. Note that $key bears the name of each field as the loop iterates.
This is hypothetical code, assuming I have the following:
Let's say I have an array and it has lots of data, integers in this sample question, but it can ANY type of data that's already sorted in some fashion in regards to the if statements.
$a = array(0,0,0,1,1,1,1,1,1,2,2,2,2,3,3,...,9,9,9);
Let's say I have a for loop with numerous if else if statements, and those can have any criteria for doing something.
for($i=0; i<count($a); i++) {
// these if statements can be anything and may or may not be related with $a
if($a[$i] == 0 && $i < 10) {
// do something
}
else if($a[$i] == 1 && $i < 20) {
// do something
}
else if($a[$i] == 2) {
// do something
}
else if($a[$i] == 3) {
// do something
}
// and so on
}
Now the question, after the first if statement iterations are done, it's never used. Once the for loop starts using the next if statement, the previous if statement(s) don't need to be evaluated again. It can use the first if statement n amount of times and so on and so forth.
Is there a way to optimize it so it doesn't have to go through all the previous if else if statements as it's looping through the data? Mind, the data can be anything, and the if statements can be any variety of conditions.
Is there a paradigm shift, that I don't see, that is required on how this should be coded up to provide optimal performance?
You could leverage call_user_func_array. You would need to build a class that stored the methods to call to perform the statements. Consider a class like this:
class MyStatements {
public function If0($a, $i) {
if($a[$i] == 0 && $i < 10) {
// do something
}
}
public function If1($a, $i) {
if($a[$i] == 1 && $i < 20) {
// do something
}
}
}
you could then do something like this:
$stmts = new MyStatements();
for($i = 0; i < count($a); i++) {
call_user_func_array(array($stmts, 'If' . strval($i)), array($a, $i));
}
I think you are spinning your wheels.
If you have a lot of data, chances are, slowness is coming from the data source not the server-side calculations.
If you do anything, you should break up your data into chunks and run portions at-a-time. And you would only need to do this if you are noticing slow load-times or bad top-load on your server.
Asynchronous connections allow you to do this with ease, using ajax you can connect to your server, pull a limited chunk of data, process it, then after that displays in the client browser, run the next chunk. Anytime you use a Web site that queries large amounts of data (ie: facebook) it does it this way.
But again, don't over-think this. You really don't need to make your procedure more complicated. If you really want a gold-star you can make an object-oriented class that processes all this for you, but I will not get into that.
PHP uses something called "short-circuit evaluation," as many other modern languages do. This means once the boolean expression has been determined to be true or false, the remaining pieces of the expression will not be evaluated.
So, you could introduce new boolean values (maybe an array of them) that tracks if a piece of code has been executed already, and if it has been, set it to false. Then use this boolean as the first condition in the "if" expression. PHP will recognize that the value of this one is set to false, and ignore the rest of the clause. This is a pretty simple route, and would keep your code mostly structured the way it is now.
Break up your for statement into multiple for statements. For your example code:
for($i=0; i<10; i++) {
if($a[$i] == 0) {
//do something
}
}
for($i=0; i<20; i++) {
if($a[$i] == 1) {
//do something
}
}
for($i=0; $i<count($a); $i++) {
if($a[$i] == 2) {
// do something
}
else if($a[$i] == 3) {
// do something
}
}
//etc...
If you are using PHP 5.3+ then you can use anonymous functions.
$a = array(0,0,0,1,1,1,1,1,1,2,2,2,2,3,3,9,9,9);
$dispatch = array(
0=>function() { echo "0"; },
1=>function() { echo "1"; },
2=>function() { echo "2"; },
3=>function() { echo "3"; },
9=>function() { echo "9"; }
);
foreach ($a as $i)
{
$dispatch[$i]();
}
Before PHP 5.3 you would have to use a map to function names, but the bottom works in PHP 5.3+ as well.
$a = array(0,0,0,1,1,1,1,1,1,2,2,2,2,3,3,9,9,9);
function foo0() { echo "0"; }
function foo1() { echo "1"; }
function foo2() { echo "2"; }
function foo3() { echo "3"; }
function foo9() { echo "9"; }
$dispatch = array(
0=>"foo0",
1=>"foo1",
2=>"foo2",
3=>"foo3",
9=>"foo9"
);
foreach ($a as $i)
{
$dispatch[$i]();
}
The above code is faster, but not completely efficient. To improve performance you would have to drop the key look up in the $dispatch array, and move forward each time the value of $a[#] changed. This assumes your $dispatch array matches the input array. You would only gain a performance improvement if the $dispatch array was very large.
$a = array(0,0,0,1,1,1,1,1,1,2,2,2,2,3,3,9,9,9);
function foo0() { echo "0"; }
function foo1() { echo "1"; }
function foo2() { echo "2"; }
function foo3() { echo "3"; }
function foo9() { echo "9"; }
$dispatch = array(
0=>"foo0",
1=>"foo1",
2=>"foo2",
3=>"foo3",
9=>"foo9"
);
reset($dispatch);
$foo = (string)current($dispatch);
$last = 0;
foreach ($a as $i)
{
$foo();
if($i != $last)
{
$foo = (string)next($dispatch);
$last = $i;
}
}
That should be about as efficient as it can be.
I'm not sure how different this is from The Solution's, but I'd thought I'd throw it out there.
function func1 () {
echo "hi\n";
}
function func2 () {
echo "bye\n";
}
$functionList = array (
0 => "func1",
1 => "func2"
);
$a = array(0,0,0,1,1,1,1,1,1,2,2,2,2,3,3,9,9,9);
$len = count($a);
for($i = 0; $i < $len; $i++) {
if (isset($functionList[$i])) {
call_user_func($functionList[$i]);
}
}
I set the keys of $functionList explicitly, since OP says they will not always be numeric. Perhaps the first 2-3 assignments could be wrapped into a class.
This verbose solution will prevent any if condition from being run after it has evaluated to false and will not iterate over the same $i value more than once except for when it transitions to the next loop.
for($i=0; i<count($a); i++) {
if($firstCondition) {
//do something
} else {
break;
}
}
for($i; i<count($a); i++) {
if($secondCondition) {
//do something
} else {
break;
}
}
If you have 10 variables that are sometimes set, other times unset, is there a quick way to echo the ones that exist without throwing an exception? These vars come from user input.
I would currently write it as
if ($var_1 != NULL) { echo $var_1; }
if ($var_2 != NULL) { echo $var_2; }
if ($var_3 != NULL) { echo $var_3; }
if ($var_other_1 != NULL) { echo $var_other_1 ; }
if ($var_other_2 != NULL) { echo $var_other_2 ; }
etc.. But is there a more quicker way?
compact function will help you
Check this function: http://php.net/manual/en/function.get-defined-vars.php
You can do something like this:
<?php
$vararr = get_defined_vars();
foreach ($vararr as $name => $value) {
echo "{$name}: {$value}<br>\n";
}
Here's another option using variable variables and a list of the variables you want to examine:
foreach( array("var_1", "var_2") as $var )
{
if( isset($$var) )
{
echo $$var;
}
}
I'm attempting to optimise the following PHP If/Else statement. Could I rewrite the code to make use to case and switch, or should I leave it as it is, or what?
Code:
if(empty($_GET['id'])){
include('pages/home.php');
}elseif ($_GET['id'] === '13') {
include('pages/servicestatus.php');
}elseif(!empty($_GET['id'])){
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if(!$rawdata){
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
}else{
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if(!$rawdata){
error_404();
}
}
Thanks
I hate switch statements, but its personal preference to be honest. As far as further optimization i'd suggest taking a look at some form of assembly language. It will give you some general ideas on how to make conditional statements more efficient. That is, it will give you a different out look on things.
if(!empty($_GET['id']))
{
if($_GET['id'] == '13')
{
include('pages/servicestatus.php');
}
else
{
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if (!$rawdata) {
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
} else {
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if (!$rawdata) {
error_404();
}
}
}
else
{
include('pages/home.php');
}
switch would be appropriate if you had several discrete values for $_GET['id'] that you were checking for.
One suggestion I can make for the sake of readability is that
} elseif (!empty($_GET['id'])) {
only needs to be
} else {
Well i don't think it's necessary to switch to a swith
but you could change
} elseif (!empty($_GET['id'])) {
to just
}else{
You may want to look into breaking up your code into a MVC form; that would make it much easier to maintain your code. At least put the last clause into another file, probably called default.php and include it. Also, you might create an array of id => file key/value sets, lookup the id, and include the file.
if (isset($_GET['id'])) {
$pages = array(
0 => 'home.php',
13 => 'servicestatus.php'
);
if (isset($pages[$_GET['id']])) {
include('pages/' . $pages[$_GET['id']]);
} else {
include('pages/default.php');
}
}
Yes, switch is evaluate once, is efficient than if elseif,
and is easier to maintain with this given structure
switch ($_GET['id'])
{
case 13: ... break;
case 0 : ... break;
default: ... break;
}
I dont know, if you should, or should not, but here I wouldnt. The main reason is, that there is at least one statement, you can omit, and then, you will have just a if-elseif-else-Statement
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
elseif (!empty($_GET['id'])) { /* code* }
is the same as
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
else { /* code* }
In the block after that, the statement if(!$rawdata) is also duplicated.