im trying to create a script that generates a number and depending on the number generated it prints something specific but it's not working properly, Heres the code:
<?php
for($zz = 1; $zz <= 20; $zz++) {
$rangen = rand(1,100);
$a = (1 <= 0) && (0 <= 7);
$b = (8 <= 0) && (0 <= 17);
echo ("<br>".$rangen . "<br>");
if($a) {
echo "a";
} elseif ($b) {
echo "b";
} else {
echo "c";
}
}
?>
The error is that it keeps printing "c" no matter what the number is.
If anyone could help that would be great, thanks.
Your conditions are all wrong. Your comparing the same numbers and never using $rangen, this is why you obtain the same result each time.
1 <= 0 and 8 <= 0 will always return false which is why you always go to the else statement.
Related
I have a table in a MySQL database that has a list of levels (1-10) and has a XP_NEEDED column, I already have a number and I want to find the level from that number (the number is an XP), I know how to do this in the way below...
Example (Short):
if ($xpLookingFor >= 100 && $xpLookingFor < 200) // Checks if not high as level 2 {
return '1'; // Would be returning Level1
}
else if ($xpLookingFor >= 200 && $xpLookingFor < 300) // Checks if not high as level 3 {
return '2'; // Would be returning Level2
}
So it checks if its higher than the current level but not as high as the level aboves xp_needed, if its as high as the next level the next if statement will handle it.
But this way has a lot of code that could possibly be shortened, what is the best way to do this? is there a built in mysql feature for this?
Im not sure if this is what you need question is not too clear.
<?php
function getLevel($xp, $maxLevel) {
for($check = 1; $check < $maxLevel; $check++)
if ($xp >= ($check*100) AND $xp < ($check*100)+100) return $check;
return $maxLevel;
}
//Param #1 is the xp level and #2 is the max level
echo getLevel(503, 10); // returns 5
echo getLevel(123, 10); //returns 1
echo getLevel(1405, 20); //returns 14
echo getLevel(1405, 10); //returns 10
?>
Because you're using elseif, the first part of the if isn't needed, you could stack them something like this.
function getLevel($xpLookingFor){
if ($xpLookingFor < 100){
return 0;
}
else if ($xpLookingFor < 200){
return 1;
}
else if ($xpLookingFor < 300){
return 2;
}
else if ($xpLookingFor < 375){
return 3;
}
else if ($xpLookingFor < 400){
return 4;
}
else {
return 'MAX!';
}
}
See example on IdeOne
I'm a beginner learning PHP. I have tried to make a loop that has a different behaviour for both even and odd numbers. I've been playing around with it for a while, yet I still can't get it to work. Has anyone got a solution?
$count = 0;
$mod = $count % 2;
while ($count < 10)
{
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
A silly mistake, mod inside while() loop.
$count = 0;
while ($count < 10) {
$mod = $count % 2; //Here
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
$count = 0;
$mod = $count %2;
Is were your problem is.
You have to use the modulus (%) operator inside the for loop. Also, there is no need to store the value from the use of the modulus operator at all, it can be compared directly inside the for-loop.
for ($count = 0; $count < 10, $count++) {
if ($count % 2 == 0) {
echo "even, ";
} else {
echo "odd, ";
}
}
You can also switch the while to a for like this.
Welcome to PHP.
Edit #1:
As you are getting a new value of $count every execution of the for-loop the old value if $count % 2 will be incorrect. It has to recalculate for every $count. First it checks if 0 is divisible by 2, then onto 1 and so forth. For every value of $count you have to check the divisibility.
In most programming languages you aren't computing a variable onto another, instead you are taking the value of the variable. Like $a = $b + $c; in that case, if you change the value of $b or $c it does not automatically update $a. Instead you have to call $a = $b + $c again. It is the same with % operator.
$count = 0;
while ($count < 10) {
$mod = $count % 2;
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
use for loop instead of while loop
for($count=0;$count<10;$count++)
{
if(($count % 2) == 0)
echo "even,";
else
echo "odd,";
}
I'm pretty new to PHP, especially object oriented php, and I'm working on some simple code, and I'm not quite sure what's wrong with what I've written so far. I'm sure it's something simple but I've beat my head against this wall for a little bit, figured I'd ask here.
class primes
{
$TestValues = array(0, 1, 2, 3, 4);
function IsPrime($number)
{
//if number is a number, perform the rest of the tests, else, return -1 (error)
if(is_numeric($number))
{
//if number is less than 0, return -1 (error)
if($number < 0)
return -1;
//if number is 0, then return 0 (false, not prime)
if($number == 0)
return 0;
//if number is greater than 1024, return -1 (error)
if($number > 1024)
return -1;
//if number is 1, return 0 (false, not prime)
if($number == 1)
return 0;
//if number is 2, return 1 (true, is prime)
if($number == 2)
return 1;
//if number mod 2 is 0, then it is even, and no even number is prime except 2, which is handled above. so return 0 (false, not prime)
if($number % 2 == 0)
return 0;
//if number has passed all previous tests, mod it by all odd numbers from 3 to its square root rounded up.
for($i = 3; $i <= ceil(sqrt($number)); $i = $i +2)
{
//if any numbers mod 3 to its square root equal 0, return 0, (false, not prime)
if($number % $i == 0)
return 0;
}
//if the number has passed all above requirements, then it is a prime number below 1024.
return 1;
else
{
return -1;
}
}
}
function TestIsPrime()
{
foreach($TestValues as $value)
IsPrime($value);
if(IsPrime() == 0)
echo($value . "=> Is not Prime");
elseif(IsPrime() == 1)
echo($value . "=> Is Prime");
elseif(IsPrime() == -1)
echo($value . "=> Is an Error");
}
function main()
{
TestIsPrime();
}
}
main();
I'm getting an error saying I don't place my array where it is currently. I'm not quite sure how the structure of php code is supposed to work with a class, so I wasn't sure where to put the $TestValues array, so I tried a few places, and none would be accepted. Also, I'm getting an error on the else statement connected to the first if(is_numeric($number)), but I couldn't be sure that the error wasn't caused by another small error I was getting. The last error is that I'm not sure where in this single page of code to call the functions inside the class. Any help would be appreciated. Once again, I'm new to doing anything useful in php, but I'm liking it so far. Thanks,
Your code was missing several braces, also you your $TestValues is part of the class, not a global variable.
I fixed the code, however you have to check the math and read the oop tutorial on php's site.
<?php
class Primes {
public $TestValues = array(0, 1, 2, 3, 4);
function IsPrime($number) {
//if number is a number, perform the rest of the tests, else, return -1 (error)
if(is_numeric($number)) {
if($number < 0 || $number > 1024)
return -1;
if($number === 0 || $number === 1 || $number % 2 === 0)
return 0;
//if number has passed all previous tests, mod it by all odd numbers from 3 to its square root rounded up.
for($i = 3; $i <= ceil(sqrt($number)); $i = $i + 2) {
//if any numbers mod 3 to its square root equal 0, return 0, (false, not prime)
if($number % $i == 0)
return 0;
}
//if the number has passed all above requirements, then it is a prime number below 1024.
return 1;
} else {
return -1;
}
}
function test() {
foreach($this->TestValues as $value) {
$t = $this->IsPrime($value);
if($t === 0) {
echo($value . "=> Is not Prime");
} elseif($t === 1) {
echo($value . "=> Is Prime");
} elseif(IsPrime() == -1) {
echo($value . "=> Is an Error");
}
echo "\n";
}
}
}
function main() {
$prime = new Primes();
$prime->test();
}
main();
You have some syntax errors in your code. I made some modification to your code now it is working :
<?php
// Check the number to be prime or not
function IsPrime($number)
{
// If the variable is not numeric, negative or greater than 1024, exit
if (!is_numeric($number) || $number < 0 || $number > 1024)
{
return -1;
}
// Perform the tests
switch($number)
{
//if number is 0 or 1, then return 0 (false, not prime)
case 0 :
case 1 :
return 0;
break;
//if number is 2, return 1 (true, is prime)
case 2 :
return 1;
break;
}
//if number mod 2 is 0, then it is even, and no even number is prime except 2, return 0 (false, not prime)
if($number % 2 == 0)
{
return 0;
}
//if number has passed all previous tests, mod it by all odd numbers from 3 to its square root rounded up.
for($i = 3; $i <= ceil(sqrt($number)); $i = $i +2)
{
if($number % $i == 0)
{
return 0;
}
}
//if the number has passed all above requirements, then it is a prime number below 1024.
return 1;
} // End of isprime function
// create an array of numbers
$testvalues = range(-2, 100);
foreach($testvalues as $value)
{
switch(isprime($value))
{
case 0 :
echo("<p style='color:gainsboro;'>" . $value . "=> Is not Prime</p>");
break;
case 1 :
echo("<p style='color:green;'>" . $value . "=> Is Prime</p>");
break;
case -1 :
echo("<p style='color:red;'>" . $value . "=> Is an Error</p>");
break;
}
}
?>
Notes :
I think you don't need a class here. It is a simple program and using
classes will make it a bit complex and php is known for its
simplicity. So keep it simple.
In some cases switch is better and more readable than if, so use it if
possible http://php.net/manual/en/control-structures.switch.php
Every language has it preferred syntax. In php it is common not to
use capitals in naming variable (except for classes) unlike other
languages
there is no main() in php
Hope this helps, excuse my english and correct me if I am wrong
The reason why u getting error for else statement is because of the closing braces } of your if statement, notice that you have a closing brace after your else condition,instead of doing that, you have to close if statement first then do else statement which in your case else means if is not numeric then do sth, also you have so many if statements which looks a little bit redundant. what you could do is to put them in same condition like if($number ==0 || $number == 2 || $number % 2 ==0 ) return 0 elseif // do sth
The reason why you can't get $Testvalues is that you need to pass the array to your function then you can use it, where did u call your TestIsPrime function? when you call it, do sth like
TestIsPrime($TestValues);
btw, it's better not to use Capital letter for variable...
I am making an ajax call in jquery
$.get("validate_isbn.php", {isbn: obj[16]},
function(answer)
{
console.log(answer);
if (answer == "valid")
{
var checked1 = $(elements[index]).val();
//$(elements[index]).val().append("<img src = 'pics/green_checkmark.png'>"); //doesn't work
//elements.after("<img src = 'pics/green_checkmark.png'>"); //sets all the elements with this pic
elements.eq(index).after("<img src='pics/green_checkmark.png' id='checkmark'>");
var checked = $(elements[index]).val();
}
});
which worked fine. I saw in the debugger that it was properly sending over the variable isbn with a isbn number from the obj array. My problem is on the php side. When I was testing, I simply had the code echo "valid" and everything worked out fine. But now when I put the real code in it stopped working:
<?php
//This algorithm is for ISBN 10
function is_isbn_10_valid($n){
$check = 0;
for ($i = 0; $i < 9; $i++)
{
$check += (10 - $i) * substr($n, $i, 1); //starting at the leftmost digit, multiple each digit by a constant, starting at 10, add the total
}
$t = substr($n, 9, 1); // tenth digit (aka checksum or check digit)
$check += ($t == 'x' || $t == 'X') ? 10 : $t; //now add the tenth digit
return $check % 11 == 0;
}
//The algorithm for ISBN 13 validation is as follows:
//Multiply each digit of teh isbn, starting at the left, with 1,3,3... etc for the entire isbn (including the check digit becuase its
//just going to be multiplied by 1 anyways.
//Add them all together, do mod 10 and voila!
function is_isbn_13_valid($n){
$check = 0;
for ($i = 0; $i < 13; $i+=2) //this does digits 1,3,5,7,9,10,11,13
{
$check += substr($n, $i, 1);
}
for ($i = 1; $i < 12; $i+=2) //this does digits 2,4,6,8,10,12
{
$check += 3 * substr($n, $i, 1);
}
return $check % 10 == 0;
}
$isbn = $_GET["isbn"];
if (strlen($isbn) = 10)
{
$result = is_isbn_10_valid($isbn);
}
else if (strlen($isbn) = 13)
{
$result = is_isbn_13_valid($isbn);
}
else
{
$result false;
}
if ($result === true)
{echo "valid";}
else if ($result === false)
{echo "not valid";}
?>
(Note: I'm sure that I can be more efficient and just return the boolean, but I refrained from that at the moment since I wasn't sure how the jquery .get would take it, as a boolean or text...)
Anyways, it doesn't work. The error on the console.log gives me:
Fatal error: Can't use function return value in write context in ...pathname here...\validate_isbn.php on line 31
On line 31, you have this:
if ($strlen($isbn) = 10)
Remove the $ on the strlen function, and change the = (assignment operator) to a == (equivalence operator). It should now look like this:
if (strlen($isbn) == 10)
You'll need to do the same a few lines after that, too.
Edit: One more thing. About five lines from the bottom, you're missing an equal sign.
$result false;
Should be:
$result = false;
I got the answer fine, but when I run the following code,
$total = 0;
$x = 0;
for ($i = 1;; $i++)
{
$x = fib($i);
if ($x >= 4000000)
break;
else if ($x % 2 == 0)
$total += $x;
print("fib($i) = ");
print($x);
print(", total = $total");
}
function fib($n)
{
if ($n == 0)
return 0;
else if ($n == 1)
return 1;
else
return fib($n-1) + fib($n-2);
}
I get the warning that I have exceeded the maximum execution time of 30 seconds. Could you give me some pointers on how to improve this algorithm, or pointers on the code itself? The problem is presented here, by the way.
Let's say $i equal to 13. Then $x = fib(13)
Now in the next iteration, $i is equal to 14, and $x = fib(14)
Now, in the next iteration, $i = 15, so we must calculate $x. And $x must be equal to fib(15). Now, wat would be the cheapest way to calculate $x?
(I'm trying not to give the answer away, since that would ruin the puzzle)
Try this, add caching in fib
<?
$total = 0;
$x = 0;
for ($i = 1;; $i++) {
$x = fib($i);
if ($x >= 4000000) break;
else if ($x % 2 == 0) $total += $x;
print("fib($i) = ");
print($x);
print(", total = $total\n");
}
function fib($n) {
static $cache = array();
if (isset($cache[$n])) return $cache[$n];
if ($n == 0) return 0;
else if ($n == 1) return 1;
else {
$ret = fib($n-1) + fib($n-2);
$cache[$n] = $ret;
return $ret;
}
}
Time:
real 0m0.049s
user 0m0.027s
sys 0m0.013s
You'd be better served storing the running total and printing it at the end of your algorithm.
You could also streamline your fib($n) function like this:
function fib($n)
{
if($n>1)
return fib($n-1) + fib($n-2);
else
return 0;
}
That would reduce the number of conditions you'd need to go through considerably.
** Edited now that I re-read the question **
If you really want to print as you go, use the output buffer. at the start use:
ob_start();
and after all execution, use
ob_flush();
flush();
also you can increase your timeout with
set_time_limit(300); //the value is seconds... so this is 5 minutes.