Using PHP trying to convert str to int - php

I really don't get why this isn't working, so please help. I'm trying to convert a str to an int and do if statements with it, but I can't for some reason. The code jumps right over the if statement like it's not even there???
<?php
$cost = $_REQUEST['cost'];
$cost = (int) $cost;
if($cost < 2){
header('Location: page.php?say=numerror');
}
?>
<input name="cost" id="cost" type="text" class="tfield" />

I have a suspicion you need:
if ($cost < 2) {
exit(header('Location: page.php?say=numerror'));
}

why do you need a conversion just use this:
<?php
$cost = $_REQUEST['cost'];
if($cost < 2 or !is_numeric($cost)){
header('Location: page.php?say=numerror');
}
?>
<input name="cost" id="cost" type="text" class="tfield" />

Try this:
<?php
$cost = $_REQUEST['cost'];
$cost = intval($cost);
if($cost < 2){
header('Location: page.php?say=numerror');
}
?>
// HTML
<input name="cost" id="cost" type="text" class="tfield" />
Here is more about intval() function at intval() PHP reference manual. I hope, that will be helpful.
If this not help you. Here is PHP function where you from string can separate integers.
<?php
function str2int($string, $concat = true) {
$length = strlen($string);
for ($i = 0, $int = '', $concat_flag = true; $i < $length; $i++) {
if (is_numeric($string[$i]) && $concat_flag) {
$int .= $string[$i];
} elseif(!$concat && $concat_flag && strlen($int) > 0) {
$concat_flag = false;
}
}
return (int) $int;
}
// Callings
echo var_dump(str2int('sh12apen11')); // int(12)
echo var_dump(str2int('sh12apen11', false)); // int(1211)
echo var_dump(str2int('shap99en')); // int(99)
echo var_dump(intval('shap99en')); // int(0)
?>
P.S Function copied from link above. Isn't mine.

Related

PHP basic: why my variable showing wrong value?

I am new to PHP. I am trying to create a simple form where user will submit there name and mark they got in the exam.
<form action="" method="post">
<input type="text" name="name" id="" placeholder="Your name">
<input type="number" name="mark" id="" placeholder="Your Mark">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST["submit"])){
$name = $_POST['name'] ;
$mark = $_POST['mark'];
if( $mark > 80 ){
$result = "A+";
}elseif($mark > 70 && $mark < 80){
$result = "A";
}
elseif($mark > 60 && $mark < 70){
$result = "A-";
}
elseif($mark > 40 && $mark < 60){
$result = "B";
}else{
$result = "Fail";
}
echo $result;
}
?>
But if I echo the result variable it is always showing 'Fail'. What is I am doing wrong? thanks
As mentioned in the comments, when comparing ranges, you need to consider the corner cases:
$mark >= 70 && $mark < 80
Also there are few ways to simplify your code: If you check for marsk >= 80 in the first IF, there is no need to check for that in the next elseif:
if( $mark >= 80 )
{
$result = "A+";
}
elseif($mark >= 70)
{
$result = "A";
}
elseif($mark >= 60)
{
$result = "A-";
}
elseif($mark >= 40)
{
$result = "B";
}
else
{
$result = "Fail";
}
echo $result;

PHP Factorial Issue

I am trying to learn PHP and compute the factorial of a number when given a input from a user, but I seem to be stumped. My first and last condition checkout but when I put a number bigger than 2 my result is always false, here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Factorial</title>
</head>
<body>
<form action="" method="GET">
Enter Number: <input type="text" name="num"><br>
<input type="submit" name ="submit">
</form>
Factorial Of Your Number:
<?php
function factorial($n){
if (ctype_digit($n))
{
if ($n <= 1)
{
echo "1";
}
else
{
echo $n * factorial($n - 1);
}
}
else
{
echo "false";
}
}
if(isset($_GET['submit']))
{
$s = $_GET["num"];
factorial($s);
}
?>
</body>
</html>
I have tried editing many variations of this line echo $n * factorial($n - 1); but all result in false or an error and I can't seem to crack this. Any ideas? Note that I am trying to keep the php in the internal body not an externalphp file.
For your recursive function to work, it needs to return a number. Otherwise your function will try to calculate $n * null which throws an error.
function factorial($n){
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
if (isset($_GET['submit'])) {
$n = intval($_GET["num"]);
echo factorial($n);
}
see this solution, find factorial of a given number in PHP?
<?php
function findFactorial($num){
$fact = 1;
for($i=1; $i<$num+1; $i++){
$fact = $fact*$i;
}
return $fact;
}
$num = 5;
print_r(findFactorial($num));
?>
Here you go:
<?php
$num = $_POST["num"];
$factorial_value = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial_value = $factorial_value * $x;
}
echo "Factorial of $num is $factorial";
?>
<form method="post">
Enter a num:
<input type="text" name="num">
<input type="submit" Value="CALCULATE YOUR FACTORIAL">
</form>

Finding the Nth Fibonacci number through input field PHP

I'm having some issues getting the input code to work with the equation. I've been trying for a while (I'm new to coding) and searching, while not being able to make it work in any way. This is what I ended up with. Can anyone help me? Thanks in advance.
<!DOCTYPE HTML>
<html>
<body>
<form action="" method="post">
<br />Choose a number to be the nth in the Fibonacci sequence: <input type="number" name="fibnum">
<input type="submit">
</form> <br /> <br />
<?php
if(isset($_POST['fibnum'])){
$fibnum = $_POST['fibnum'];
function fibRec($fibnum){
if ($fibnum < 0){
echo "There are no Fibonacci numbers of negative values.";
}
elseif ($fibnum == 0){
echo "0";
}
elseif ($fibnum == 1){
echo "1";
}
else {
$sum = fibRec($fibnum-1)+fibRec($fibnum-2);
echo $sum;
}
}
$fib = fibRec($fibnum);
echo $fib;
}
?>
</body>
</html>
to make it work all you need to do is change the echo's to returns like so:
<?php
$_POST['fibnum']=11;
if(isset($_POST['fibnum'])){
$fibnum = $_POST['fibnum'];
function fibRec($fibnum){
if ($fibnum < 0){
return ( "There are no Fibonacci numbers of negative values.");
}
elseif ($fibnum == 0){
return ("0");
}
elseif ($fibnum == 1){
return ("1");
}
else {
$sum = fibRec($fibnum-1)+fibRec($fibnum-2);
return ($sum);
}
}
$fib = fibRec($fibnum);
echo $fib;
}
?>
working demo: http://ideone.com/e0xeY7
you were pushing integers into echo. in a recursive formula, returning the value goes back to the calling entity, not automatically outside the function.
Take a look at this:
<!DOCTYPE HTML>
<html>
<body>
<form action="" method="post">
<br />Choose a number to be the nth in the Fibonacci sequence: <input type="number" name="fibnum">
<input type="submit">
</form> <br /> <br />
<?php
if(isset($_POST['fibnum'])){
$fibnum = $_POST['fibnum'];
function fibRec($fibnum){
if ($fibnum < 0){
echo "There are no Fibonacci numbers of negative values.";
}
elseif ($fibnum == 0){
return 0;
}
elseif ($fibnum == 1){
return 1;
}
else {
$sum = fibRec($fibnum-1)+fibRec($fibnum-2);
return $sum;
}
}
$fib = fibRec($fibnum);
echo $fib;
}
?>
</body>
</html>
You can also use PHI constant associated with golden ratio to calculate nth fibonacci number. it is considered that fibonnaci number until 5th iteration are not as per golden ratio so you can have it like below :
<?php
$fibnum = intval($_POST['fibnum']);
const PHI = 1.6180339887;
$f = [0, 1, 1, 2, 3];
echo getNthFibo($fibnum);
function getNthFibo($i)
{
if($i < 5){
return $f[$i];
}
// Starting from 5th iteration of fibo function
$n = 5;
$fn = 3;
while ($n < $i) {
$fn = round($fn * PHI);
$n++;
}
return $fn;
}

Fibonacci sequence calculations? [duplicate]

This question already has answers here:
Create a mechanism to pass in a positive integer and display all the values of the Fibonacci series up to and including the specified value
(2 answers)
Closed 8 years ago.
How would I create a mechanism to pass in a positive integer and display the operand, the Fibonacci series number of the operand and the sum of all the values of the Fibonacci series up to and including the specified value?
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="main.css"/>
<title>Fib Activity 3</title>
</head>
<body>
<h1>Pick Category Using GET</h1>
Films
Music
Books
<br />
<h2>Fibonacci</h2>
<form method="get" action="fib3.php">
<fieldset>
<label for="powerof">Fibonacci: </label>
<input type="text" name="powerof" value="<?php echo $_GET['powerof']; ?>"/>
<input type="submit" name='Go' value="Calculate" />
</fieldset>
</form>
<?php
$message = 'The fibonacci sequence is: <br />1<br />2<br />';
$powerof = 0;
$max = 10;
$temp = $max;
if (isset($_GET['powerof'])) {
$powerof = $_GET['powerof'];
}
if ($powerof > 100) {
$powerof = 100;
$message = 'Sorry, your input was too high. I converted it to the maximum value of 100.<br />The fibonacci sequence is: <br />1<br />2<br />';
}
$x = 0;
$y = 1;
$z = 0;
$counter = 0;
while ($counter < $powerof) {
if ($counter <= 1) {
$z = 1;
} else {
$z = $x + $y;
}
echo ($z. "<br />");
$x = $y;
$y = $z;
$counter++;
}
?>
</body>
</html>
all help is appreciated
First off, you aren't quite getting the Fibonacci series correct. The first number in the Fibonacci series is 0. The script I wrote here assumes that $powerof needs to be at least 1 (this can be easily changed if you need).
I also wrote this using a recursive function which takes the number you are going to. the first number, and the second number. It will loop through by calling itself and each time, it will print out the fibonacci series at the number.
<?php
$powerof = 0;
if (isset($_GET['powerof'])) {
$powerof = $_GET['powerof'];
}
$message = 'The fibonacci sequence is:';
if ($powerof > 100) {
$powerof = 100;
$message = 'Sorry, your input was too high. I converted it to the maximum value of 100.<br />The fibonacci sequence is:';
}
echo $message;
$first = 0;
$second = 1;
if ($powerof > 1) {
echo '<br>0<br>1';
} else if ($powerof < 1) {
echo ' Invalid input';
} else {
fib($powerof, $first, $second);
}
function fib($powerof, $first, $second) {
if( $powerof > 0 ) {
$sum = $first + $second;
$first = $second;
$second = $sum;
echo $sum.'<br>';
fib($n-1, $first, $second);
}
}
?>
I hope this all makes sense, if you have any more questions, let me know

how do i generate series of numbers?

i need help to generate series of number and it should be generate series of number when
form is submitted i have code but it not working properly?
For Example I Want Like This
00500
00501
00502
00503 and so on...
Here My Code
$random = rand(500,999);
$new_val = $random+1;
for($i=1;$i<=$new_val;$i++)
{
if( strlen($i)==1 )
{
$say='0000'.$i;
}
elseif( strlen($i)==2 )
{
$say='000'.$i;
}
elseif( strlen($i)==3 )
{
$say='00'.$i;
}
elseif( strlen($i)==4 )
{
$say='0'.$i;
}
elseif( strlen($i)==5 )
{
$say=$i;
}
}
<form method="post">
<input class="input_field" readonly="readonly" type="text"
name="sno" id="sno" value="<?=$say?>" >
<input type="submit" name="test" value="submit" />
</form>
Use sprintf to format it:
<?php
$start = rand(500, 999);
for ($i = 1; $i <= $start; $i++) {
$num = sprintf("%05d", $i);
echo $num;
}
?>
As Blender says, use sprintf to format your numbers
$start = rand(500, 999);
for ($i = $start; $i <= 999; $i++) {
$num = sprintf("%1$05d", $i);
echo $num . '<br>';
}
Note that the form must contain an "action" attribute

Categories