Divide a textarea strings into groups depends on blank space - php

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.

Related

how to determine the sequence number of odd /even numbers using php

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++;
}
?>

Checking if a number is a Fibonacci number through a loop

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';
}

How can i build a PHP array with a limited number of possibilities

I am trying to build a piece of code that prints the line 5 times and there are only two possible outcomes. I also want one of the outcomes to only have the possibility of appearing twice.
<?php
function abe( $number ) {
$shoot = Array("alpha", "bravo");
?>
<h1> Hello <?php echo $number; ?> You are on team <?php echo $shoot[array_rand($shoot)]; ?> </h1>
<?php
}
?>
<?php abe( '1'); ?>
<?php abe( '2'); ?>
<?php abe( '3'); ?>
<?php abe( '4'); ?>
<?php abe( '5'); ?>
So ideally i want it to print five times only. I also want the "Bravo" to be printed a max amount of 2 times. How can I make it so there are only two instances of Bravo allowed?
So this may print....
Hello 1 You are on team alpha
Hello 2 You are on team alpha
Hello 3 You are on team alpha
Hello 4 You are on team alpha
Hello 5 You are on team alpha
There is a possibility that Bravo will not even print once. How can i be sure it will print 2 times?
Untested, but this should be dynamic to deal with any number of players:
<?php
function abe( $number ) {
// Input: Array Input of numbers or Names
// Output: Team selection for each member of array Alpha||Bravo, where there can only be 2 Bravo
$b = 0;
$r = "";
foreach($number as $n){
$p = rand(0,1);
if($p == 1){
$b++;
}
if($b > 2){ $p = 0; }
$r .= "<h1 pick='$p'>Hello $n You are on team " . (!$p?"Alpha":"Bravo") . " </h1>\r\n";
}
return $r;
}
echo abe(array(1,2,3,4,5));
?>
EDIT
Per your comments, here is another version that will force Bravo 2 times:
<?php
function abe( $number ) {
// Input: Array Input of numbers or Names
// Output: Team selection for each member of array Alpha||Bravo, where there can only be 2 Bravo
$b = 0;
$c = count($number);
$r1 = rand(1,$c);
$r2 = rand(1,$c);
if($r1 == $r2){
$r2++;
if($r2 > $c){
$r2 -= 2;
}
}
$r = "";
foreach($number as $k => $n){
if($k == $r1 || $k == $r2){
$r .= "<h1 pick='$k'>Hello $n You are on team Bravo</h1>\r\n";
} else {
$r .= "<h1 pick='$k'>Hello $n You are on team Alpha</h1>\r\n";
}
}
return $r;
}
echo abe(array(1,2,3,4,5));
?>

Hidden HTML form fields saving the state

So I've been at this a while. Too long...
The problem I'm having is that all the hidden value fields change too the input you just put in (at least according to the source code).
This is how I’m trying to change them..(6 of these for a count, avg etc.)
<input type="hidden" name="sum" value="<?php print $sum ?>" />
This is the php file
<?php
$input = htmlspecialchars($_POST['num']);
$tempray = array($input);
//Also tried things like $sum = $sum + $input but no luck
$sum = array_sum($tempray);
$count = count($tempray);
$avg = ($sum/$count);
$max = max($tempray);
$min = min($tempray);
$posint = $poscount;
if( is_int( $input ) and $input >= 0 and $input % 2 == 0 ) {
$poscount = $poscount + 1;
}
if ($input != 0 AND $input != null){
include 'index.html.php';
}else{
include 'results/index.html.php';
}
?>
Not sure why this wouldn't work?

Check if any number in the array is not a int [duplicate]

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;
}

Categories