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;
}
Related
Take an input string (via form post) which can contain single-digit numbers, letters, and question marks, and check if there are exactly 2 question marks between every pair of two numbers that add up to 12.
If so, return "Yes", otherwise it should return "No". If there aren't any two numbers that add up to 12 in the string, return "No".
For example: if str is "arrb7??5xxbl8??eee4" then your program should return true because there are exactly 2 question marks between 7 and 5, and 2 question marks between 8 and 4 at the end of the string.
enter code here
<?php
$value = $_POST['temp'];
$len = strlen($value);
// $splt = explode(",",$value);
// var_dump($splt);
// foreach($splt as $result)
// {
// echo $result ."<br>";
// }
$i=0;
strpos($value[i]);
if(is_numeric($value)&& $len < 12)
{
echo $value;
}
else
{
echo 'no';
}
// $temp = explode($value);
// if($value == )
// is_numeric($value);
enter code here
From your comments in your code, I understand you are trying to explode ','. That doesn't relate to any part of the logic. You might need to explode to split your string based on "??". To extract those pair of numbers before adding them, there are pre-defined methods like preg_match_all(). filter_var(), so on. Here's an example working:
<?php
$string = 'arrb7??5xxbl8??eee4';
$terms = explode("??",$string);
$success = true;
for ($counter=1; $counter < count($terms); $counter+=1) {
$num1 = ((int) filter_var($terms[$counter-1], FILTER_SANITIZE_NUMBER_INT)) % 10;
$num2 = ((int) filter_var($terms[$counter], FILTER_SANITIZE_NUMBER_INT));
$sum = $num1+((string)($num2))[0];
if ($sum != 12)
{
$success = false;
break;
}
}
echo $success ? "Yes" : "No";
?>
I created this function to converting numbers to words. And how I can convert words to number using this my function:
Simple function code:
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$n = "98"; // Input number to converting
if($n < 10 && $n > -1){
echo $array[$n];
}
if($n == 10 OR $n == 20 OR $n == 30 OR $n == 40 OR $n == 50 OR $n == 60 OR $n == 70 OR $n == 80 OR $n == 90 OR $n == 100){
echo $array[$n];
}
if(mb_strlen($n) == 2 && $n[1] != 0)
{
$d = $n[0]."0";
echo "$array[$d]У ".$array[$n[1]];
}
My function so far converts the number to one hundred. How can I now convert text to a number using the answer of my function?
So, as #WillParky93 assumed, your input has spaces between words.
<?php
mb_internal_encoding("UTF-8");//For testing purposes
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$postfixes = array("3" => "ВУ");
$n = "98"; // Input number to converting
$res = "";
//I also optimized your conversion of numbers to words
if($n > 0 && ($n < 10 || $n%10 == 0))
{
$res = $array[$n];
}
if($n > 10 && $n < 100 && $n%10 != 0)
{
$d = intval(($n/10));
$sd = $n%10;
$ending = isset($postfixes[$d]) ? $postfixes[$d] : "У";
$res = ($array[$d * 10]).$ending." ".$array[$sd];
}
echo $res;
echo "\n<br/>";
$splitted = explode(" ", $res);
//According to your example, you use only numerals that less than 100
//So, to simplify your task(btw, according to Google, the language is tajik
//and I don't know the rules of building numerals in this language)
if(sizeof($splitted) == 1) {
echo array_search($splitted[0], $array);
}
else if(sizeof($splitted) == 2) {
$first = $splitted[0];
$first_length = mb_strlen($first);
if(mb_substr($first, $first_length - 2) == "ВУ")
{
$first = mb_substr($first, 0, $first_length - 2);
}
else
{
$first = mb_substr($splitted[0], 0, $first_length - 1);
}
$second = $splitted[1];
echo (array_search($first, $array) + array_search($second, $array));
}
You didn't specify the input specs but I took the assumption you want it with a space between the words.
//get our input=>"522"
$input = "ПАНҶ САД БИСТ ДУ";
//split it up
$split = explode(" ", $input);
//start out output
$c = 0;
//set history
$history = "";
//loop the words
foreach($split as &$s){
$res = search($s);
//If number is 9 or less, we are going to check if it's with a number
//bigger than or equal to 100, if it is. We multiply them together
//else, we just add them.
if((($res = search($s)) <=9) ){
//get the next number in the array
$next = next($split);
//if the number is >100. set $nextres
if( ($nextres = search($next)) >= 100){
//I.E. $c = 5 * 100 = 500
$c = $nextres * $res;
//set the history so we skip over it next run
$history = $next;
}else{
//Single digit on its own
$c += $res;
}
}elseif($s != $history){
$c += $res;
}
}
//output the result
echo $c;
function search($s){
global $array;
if(!$res = array_search($s, $array)){
//grab the string length
$max = strlen($s);
//remove one character at a time until we find a match
for($i=0;$i<$max; $i++ ){
if($res = array_search(mb_substr($s, 0, -$i),$array)){
//stop the loop
$i = $max;
}
}
}
return $res;
}
Output is 522.
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++;
}
?>
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';
}
I have a textarea in my html form where user can enter numbers and after the form submit,php will echo sum of the numbers
for example, If I enter
1
2
it will output,
sum is 3
My requirement is, if I put blank space(one or more), between each set of devices, it has to process each set of devices separately
for example,
1
2
3
4
and above should display output as
sum is 3
sum is 7
But using below code I am getting output like
sum is 10
My Code:
<html>
<body>
<div class="cal-main">
<form id="form1" name="form1" action=" " method="post" >
<div class="input">Enter Numbers</div>
<div class="output"><span><textarea class="textarea" name="numbers" ></textarea></span></div>
<div class="submit1">
<input id="first_submit" type="submit" name="first_submit" value="first_submit" />
</div>
</form>
<?php
if (isset($_POST['first_submit']))
{
?>
<textarea onclick="this.select()" name="output_textarea" id="output_textarea" cols="100" rows="25" readonly value="">
<?php
$numbers = $_POST['numbers'];
$digits = explode(PHP_EOL.PHP_EOL, $numbers); // Favor PHP_EOL (end of line) to avoid cross OS issues
foreach($digits as $digit)
{
$count = array_sum(explode(PHP_EOL, $digit));
echo "sum is $count".PHP_EOL;
}
}
?>
</textarea>
</div>
</body>
</html>
PHP FIDDLE SETUP
I would use preg_split and \r?\n:
$digits = preg_split('#(\r?\n){2,}#',$numbers); //2 or more \r\n (\r optional)
foreach($digits as $key => $digit)
{
$count = array_sum(preg_split('#\r?\n#', $digit));
echo "sum is $count".PHP_EOL;
if($key < count($digits)-1) echo '<br />';
}
Output:
sum is 3
sum is 7
$numbers = $_POST['numbers'];
$digits = explode("\n", $numbers); // explode by next line
$sums = array(); // array to put sums in
$i = 0;
foreach($digits as $digit) {
$digit = trim($digit); // remove next line
if(is_numeric($digit))
$sums[$i] += $digit; // sum up
else
$i++; // next index (row wasn't number)
}
print_r($sums);
// Output: Array ( [0] => 3 [1] => 7 )
Using preg_split is more appropriate, though new line could be different on different OS. My solution:
function split_new_lines($string){
return preg_split('/\R/', $string);
}
$input = "
1
2
3
4
5
";
$lines = split_new_lines($input);
$sums = array();
$sum = null;
foreach($lines as $line){
$line = trim($line);
if(is_numeric($line))
{
if($sum === null)
$sum = (int)$line;
else
$sum += (int)$line;
}
else
{
if($sum !== null)
$sums[] = $sum;
$sum = null;
}
}
if($sum !== null)
$sums[] = $sum;
notice that PHP_EOL is used to find the newline character in a cross-platform-compatible way. i have tested your code on in a windows/php 5.4.3 and it works as described above. when i run your fiddle, i get the error.