how to determine the sequence number of odd /even numbers using php ?
example ,i want output like here
odd numbers (1,3,5,7,9)
output
1 = 1
3 = 2
5 = 3
7 = 4
9 = 5
even numbers (2,4,6,8,10)
output
2=1
4=2
6=3
8=4
10=5
how code to make this function in php?
edit/update
if input 1 then output = 1 , if input 3 then output = 2, if input 21 then output= 11, etc,,
Try out this
php code
<?php
$result = '';
if(isset($_POST['value'])){
//assign POST variable to $num
$num = $_POST['value'];
$count = 0;
//for even numbers
if($num % 2 == 0){
$count = $num/2;
$result = "The Number ".$num." is Even on ".$count;
}else {
//if you know about sequences and series, you can understand it :P
$count = (($num-1) / 2)+1;
$result = "The Number ".$num." is Odd on ".$count;
}
}
?>
HTML COde
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="text" name="value"/>
<input type="submit" value="Check"/><br/>
<?php echo $result;?>
</form>
It is working correctly :P
<?php
$evenLimit = 10;
$oddLimit = 9;
$count = 1;
for ($x = 1; $x <= $oddLimit; $x = $x + 2) {
echo $x . "=" . $count . "<br>";
$count++;
}
echo "<br>";
$count = 1;
for ($x = 2; $x <= $evenLimit; $x = $x + 2) {
echo $x . "=" . $count . "<br>";
$count++;
}
?>
Related
so the task I'm trying to complete here is comparing a user input number against the fibonacci sequence and if it is a fibonacci number the program will echo true, if not it will echo false.
Can someone tell me where I'm going wrong?
this is my first file:
<?php
function print_fibonacci($n){
$first = 0;
$second = 1;
echo "Fibonacci Series: \n";
echo $first.' '.$second.' ';
for($i=2;$i<$n;$i++){
$third = $first + $second;
echo $third.' ';
$first = $second;
$second = $third;
}
}
/* Function call to print Fibonacci series upto 6 numbers. */
print_fibonacci(16);
?>
<form method="POST" action="fibonacci3.php"><br>
<label>Input a number to check if it is fibonacci or not.</label><br>
<input name="fib" type="text" placeholder="#" /><br>
<input type="submit" value="OK!" />
</form>
This outputs the fibonacci sequence until the 16th fibonacci number, and is followed by a form which allows a user to enter a number.
The next file is fibonacci3.php as referenced in the form.
<?php
include "fibonacci2.php";
$n = $_POST["fib"];
function fibonacci($n) {
//0, 1, 1, 2, 3, 5, 8, 13, 21
/*this is an error condition
returning -1 is arbitrary - we could
return anything we want for this
error condition:
*/
if((int)$n <0){
return -1;
echo "False";
}
if ((int)$n == 0){
return 0;
echo "0";
}
if((int)$n == 1 || $n == 2){
return 1;
}
$int1 = 1;
$int2 = 1;
$fib = 0;
for($i=1; $i<=$n-2; $i++ )
{
$fib = $int1 + $int2;
//swap the values out:
$int2 = $int1;
$int1 = $fib;
}
if ($fib = $int1 + $int2 && $n == $fib){
echo "True!";
} else {
echo "False!";
}
return $fib;
}
fibonacci((int)$n);
?>
I thought this might be correct but it's not outputting anything when the user inputs a number.
$n = 'Your number';
$dRes1 = sqrt((5*pow($n, 2))-4);
$nRes1 = (int)$dRes1;
$dDecPoint1 = $dRes1 - $nRes1;
$dRes2 = sqrt((5*pow($n, 2))+4);
$nRes2 = (int)$dRes2;
$dDecPoint2 = $dRes2 - $nRes2;
if( !$dDecPoint1 || !$dDecPoint2 )
{
echo 'True';
}
else {
echo 'False';
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to write a program to find the maximum gap between two 1s in a binary equivalent of a decimal number. For example for 100101: the gap is 2 and for 10101: the gap is 1.
<?php
$numberGiven = 251;
$binaryForm = decbin($numberGiven);
$status = false;
$count = 0;
for($i = 0; $i < strlen($binaryForm); $i++)
{
var_dump($binaryForm[$i]);
if($binaryForm[$i] == 1)
{
$status = false;
$count = 0;
}
else
{
$status = true;
$count += 1;
}
}
echo "count = " . $count . "<br>";
echo $binaryForm;
?>
but i was not successfull..
First use regex to find "0" groups, then sort by length, descending—take the first one in the list, and get it's length:
$numberGiven = 37;
$binaryForm = decbin($numberGiven);
// get all groups of "0", put list in $matches
preg_match_all('/(0+)/', $binaryForm, $matches_all);
$matches = $matches_all[0];
// sort descending
rsort($matches, SORT_STRING);
// get first `$matches[0]` and print string length
echo 'count = ' . strlen($matches[0]) . '<br>';
echo $binaryForm;
UPDATED: based on Mark Baker's comments below.
UPDATE #2: As brought up by afeijo in the comments below, the above does not exclude ending zeros. Here's a solution for that:
preg_match_all('/(0+)1/', $binaryForm, $matches_all);
$matches = $matches_all[1];
I would use the binary right-shift operator >> and iteratively shift by 1 bit and check if the current rightmost bit is a 1 until I've checked all the bits. If a 1 was found, the gap between the previous 1 is calculated:
foreach(array(5,17,25,1223243) as $number) {
$lastpos = -1;
$gap = -1; // means there are zero or excatly one '1's
// PHP_INT_SIZE contains the number of bytes an integer
// will consume on your system. The value * 8 is the number of bits.
for($pos=0; $pos < PHP_INT_SIZE * 8; $pos++) {
if(($number >> $pos) & 1) {
if($lastpos !== -1) {
$gap = max($gap, $pos - $lastpos -1);
}
$lastpos = $pos;
}
}
echo "$number " . decbin($number) . " ";
echo "max gap: {$gap}\n";
}
Output:
5 101 max gap: 1
17 10001 max gap: 3
25 11001 max gap: 2
1223243 100101010101001001011 max gap: 2
What you currently are doing is reseting the count each time you find a 1.
You need to keep track of the current max value:
$count = 0;
$maxCount = 0;
and where you set $count = 0 you should also do
if ($count > $maxCount)
$maxCount = $count;
$count = 0;
then
echo "count = " . $maxCount . "<br>";
In all:
<?php
$numberGiven = 251;
$binaryForm = decbin($numberGiven);
$status = false;
$count = 0;
$maxCount = 0;
for($i = 0; $i < strlen($binaryForm); $i++)
{
// Don't count leading zeroes.
if ($status == false && $binaryForm[$i] == 0) continue;
$status = true;
var_dump($binaryForm[$i]);
// We've found a 1. Remember the count.
if($binaryForm[$i] == 1)
{
if ($count > $maxCount)
$maxCount = $count;
$count = 0;
}
// We found a 0. Add one to count.
else
{
$count += 1;
}
}
echo "count = " . $count . "<br>";
echo $binaryForm;
?>
Disclaimer: Code not tested
is that possible to sum variable static values in the while or for loop? i have code and working on it but it sum variables only one time?
Here My Code
session_start();
$length=count($_SESSION['product1']);
$shipping2='280';
$shipping3='680';
$newshipping='0';
$newshipping1='0';
$i='0';
while($i= <$length)
{
$newshipping=$shipping2+$shipping3;
$newshipping1=$newshipping+$shipping2;
}
For Example I want like this
$shipping2='280'; should be sum with every result of $newshipping1
`$newshipping1`= $shipping2='280' + $shipping3='680' = `$newshipping1`=960
+ $shipping2='280'??
'$newshipping1`=960+ $shipping2=280+ $shipping2=280+ $shipping2=280 .....
when ever new product1 enter it should be add $shipping2=280
in the result of `$newshipping1`
I have completed my code here my final code
$length=count($_SESSION['product1']);
$shipping2=280;
$shipping3=680;
$newshipping=0;
for($i=0; $i <$length; $i++) {
if($i == 1) {
$newshipping = $shipping2+$shipping3;
} else if($i <= 100) {
$newshipping = $newshipping+$shipping2;
}
}
Your logic seems a bit confusing, however you can sum several integers. If you are trying to figure out the final amount of several iterations you should:
$shipping_one = 680;
$shipping_two = 260;
$shipping_three = 0;
$finalShipping = array();
while($i= <$length)
{
$finalShipping[] = $shipping_one + $shipping_two + $shipping_three;
}
$finalTotal = array_sum($finalShipping);
If you can clarify your question, I can clarify my answer.
this will be ((680) + (4 * 280)) like you explained in your last comment.
$length = 1;
echo "Test with $length : ".getShippingTotal($length)." <br />";
$length = 2;
echo "Test with $length : ".getShippingTotal($length)." <br />";
$length = 3;
echo "Test with $length : ".getShippingTotal($length)." <br />";
$length = 4;
echo "Test with $length : ".getShippingTotal($length)." <br />";
$length = 5;
echo "Test with $length : ".getShippingTotal($length)." <br />";
function getShippingTotal($length) {
$shipping2=280;
$shipping3=680;
$total = 0;
for($i=0; $i < $length; $i++) {
if($i == 0) {
$total += $shipping2+$shipping3;
} else {
$total += $shipping2;
}
}
return $total;
}
I have tested it and it gave me:
Test with 1 : 960
Test with 2 : 1240
Test with 3 : 1520
Test with 4 : 1800
Test with 5 : 2080
This question already has answers here:
More concise way to check to see if an array contains only numbers (integers)
(6 answers)
Closed 10 years ago.
I made a form that you can send numbers with for example
1 2 3 4 5 6 7 8 9 10
And then I made a PHP code that will grab these numbers inside a array & loop that will calculate how many array items there is and then do the calculations.
I used is_numeric to check if the array contains only ints.
But for some reason it doesn't really work.
<?php
$total = null;
$number = $_POST['number'];
$numbers = explode(" ", $number);
foreach($numbers as $number) {
$total = $total + $number;
}
$notnumber = '<center>You must enter a number</center>';
$empty = '<center>The field is empty.</center>';
if ($numbers == is_numeric($numbers) && $total != null) {
$avg = $total / $number;
echo '<center>Avarge is: <b>'.$avg.'</b></center>';
} else if ($_POST['number'] == "") {
echo $empty;
} else if ($numbers != is_numeric($numbers)) {
echo $notnumber;
}
?>
This is the form
<form action="index.php" method="post">
<input type="text" name="number" class="input"><br /><br />
<input type="submit" value="Calculate results">
</form>
What happens:
When I enter numbers, it will echo the error "$notnumbers" yet they are numbers.
What have I done wrong?
Thanks.
if($numbers == is_numeric($numbers) ... is not correct
use
if (is_numeric($numbers) && $total != null) {
The better function is ctype_digit
Please try this and do not use yours!
//$_POST['number'] = '1 2 3 4 5 6 7 8 9 10';
$notnumber = '<center>You must enter a number</center>';
$empty = '<center>The field is empty.</center>';
if(!isset($_POST['number']) || strlen($_POST['number']) <= 0){
echo $empty;
}
else{
if( !preg_match('/^([1-9]{1})([0-9]*)(\s)([0-9]+)/', $_POST['number']) ){
echo $notnumber;
}else{
$total = null;
$number = $_POST['number'];
$numbers = explode(" ", $number);
//remove after test
echo "<pre>";
print_r($numbers);
echo "</pre>";
//end remove
$total = array_sum($numbers);
//count(array) = number of elements inside $array
$avg = $total / count($numbers);
echo '<center>Avarge is: <b>'.$avg.'</b></center>';
}
}
This is incorrect: $numbers == is_numeric($numbers).
Alternate Solution:
You could try this, providing you count 0 as an invalid number.
$number = $_POST['number'];
$numbers = explode(" ", $number);
$total = 0;
foreach($numbers as &$number) {
// covert value to integer
// any non-numerics become 0
$number = (int) $number;
$total += $number;
}
Now you won't have to worry about checking for is_numeric or is_int because they'll all be ints. You'll just need to check for 0 values instead.
Extra Tip:
<center> tag is also deprecated in HTML.CSS should be used to display centred text.
try this i solve some problem on code
<?php
$total = NULL;
$number = #$_POST['number'];
$numbers = explode(" ", $number);
$Num=0;
foreach($numbers as $number) {
$total = $total + $number;
$Num++;
}
$notnumber = '<center>You must enter a number</center>';
$empty = '<center>The field is empty.</center>';
if (is_array($numbers) && $total != NULL) {
$avg = $total / $Num;
echo '<center>Avarge is: <b>'.$avg.'</b></center>';
} else if (!isset($_POST['number'])) {
echo $empty;
} else if (!is_numeric($number)) {
echo $notnumber;
}
I have an array for flash cards, and using shuffle I am outputting 15 unique cards, 3 each for 5 different categories.
What I want to do is create these card sets for about a dozen people on the same web page, but the part I can't figure out is how to make it so each complete set is unique and doesn't repeat from a set given to any other user.
A short code sample with a brief explanation would be the most helpful to me.
Here is the code I modified to my needs. Not much changed really.
<?php
/* original source:
* 3d10-engine.php
* by Duane Brien
*/
if (empty($_POST)) {
for ($i = 1; $i < 16; $i++) {
$numbers['ALL'][] = $i;
}
$picks = array();
$letters = array ('ALL');
foreach ($letters as $letter) {
for ($i = 0;$i < 10;$i++) {
shuffle($numbers[$letter]);
$chunks = array_chunk($numbers[$letter], 5);
$cards[$i][$letter] = $chunks[0];
if ($letter == 'N') {
$cards[$i][$letter][2] = ' '; // Free Space
}
}
foreach ($numbers[$letter] as $number) {
$balls[] = $letter.$number;
}
shuffle($balls);
}
$cardsstr = serialize($cards);
$ballsstr = serialize($balls);
$picksstr = serialize($picks);
} else {
$cards = unserialize($_POST['cardsstr']);
$balls = unserialize($_POST['ballsstr']);
$picks = unserialize($_POST['picksstr']);
array_unshift($picks, array_shift($balls));
echo "<h1>Just Picked: " . $picks[0] . "</h1>";
$cardsstr = serialize($cards);
$ballsstr = serialize($balls);
$picksstr = serialize($picks);
}
?>
Picks : <?php echo implode(',', $picks) ?>
<form method='post'>
<input type='hidden' name='cardsstr' value='<?php echo $cardsstr ?>' />
<input type='hidden' name='ballsstr' value='<?php echo $ballsstr ?>' />
<input type='hidden' name='picksstr' value='<?php echo $picksstr ?>' />
<input type='submit' name='cards' value='next number' />
</form>
Start Over
<?php
foreach ($cards as $card) {
echo "<table border='1'>";
echo "<tr><td>A</td><td>B</td><td>C</td><td>D</td><td>E</td></tr>";
for ($i = 0; $i < 5; $i++) {
echo "<tr><td>" . $card['B'][$i] . "</td><td>" .$card['I'][$i] . "</td><td>" . $card['N'][$i] . "</td>";
echo "<td>" . $card['G'][$i] . "</td><td>" . $card['O'][$i] . "</td></tr>";
}
echo "</table>";
}
?>
Since you have more options in each set, random pick is enough to achieve unique final result.
I mean don't make this thing more complex.
Try this sample
<?php
//Initialize your 5 sets here
$numbers['B'] = range(1,15);
$numbers['I'] = range(16,30);
$numbers['N'] = range(31,45);
$numbers['G'] = range(45,60);
$numbers['O'] = range(61,75);
//My Assumption is you to pick 3 from each
while(TRUE){
$rand = rand(0,5);
if(count($numbers_B) < 3 && !in_array($numbers['B'][$rand]){
$numbers_B[] = $numbers['B'][$rand];
}
$rand = rand(0,5);
if(count($numbers_I) < 3 && !in_array($numbers['I'][$rand]){
$numbers_I[] = $numbers['I'][$rand];
}
$rand = rand(0,5);
if(count($numbers_N) < 3 && !in_array($numbers['N'][$rand]){
$numbers_N[] = $numbers['N'][$rand];
}
$rand = rand(0,5);
if(count($numbers_G) < 3 && !in_array($numbers['G'][$rand]){
$numbers_G[] = $numbers['G'][$rand];
}
$rand = rand(0,5);
if(count($numbers_O) < 3 && !in_array($numbers['O'][$rand]){
$numbers_O[] = $numbers['O'][$rand];
}
if( count($numbers_B) == 3 && count($numbers_I) == 3 && count($numbers_N) == 3 &&
count($numbers_G) == 3 && count($numbers_O) == 3 ){
break;
}
}
$result = $numbers_B + $numbers_I + $numbers_N + $numbers_G + $numbers_O; ?>
Here $result value should be unique, And I consider number of sets is constant. If it is dynamic, then try the same logic with two dimensional array.
Just store the prepared sets in an array and then check each shuffle if it exists in the array using the already (in_array function) or not, if it does then shuffle again.