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?
Related
I need to generate random IDs that validate against the criteria for Saudi IDs shown in this question:
Saudi Iqama/National Identity number field validation
I've tried the following code:
$random_numbers = [];
while(count($random_numbers) < 1000000000){
do {
$random_number = mt_rand(1000000000,9000000000);
}
while (in_array($random_number, $random_numbers));{
$type = substr ( $random_number, 0, 1 );
if($type != 2 && $type != 1 ) break;
$sum = 0;
for( $i = 0 ; $i<10 ; $i++ ) {
if ( $i % 2 == 0){
$ZFOdd = str_pad ( ( substr($random_number, $i, 1) * 2 ), 2, "0", STR_PAD_LEFT );
$sum += substr ( $ZFOdd, 0, 1 ) + substr ( $ZFOdd, 1, 1 );
}else{
$sum += substr ( $random_number, $i, 1 );
}
}
return $sum%10 ? break : echo $random_number;
----------
echo "<br>";
$random_numbers[] = $random_number;}
}
Disclaimer: I'm not 100% sure on the validation required etc. for Saudi ID numbers and have only briefly looked at the answers supplied in the linked question
Okay, so, my understanding is that you need to generate a random id that:
Matches the pattern/format:
[12]\d{9}
Validates against the criteria show in the linked question:
Saudi Iqama/National Identity number field validation
To do this we need to create a couple of functions; one to generate IDs and one to validate the IDs against the given criteria.
Generate the ID
Simply generating an ID is simple enough. We can use the random_int function in PHP with a loop. If we enclose the code to generate the ID inside of a do...while... loop then we can execute the code and validate the ID repeatedly until we get a valid one.
function getRandomSaudiId() : int
{
do {
$saudiId = (string) random_int(1,2);
for($i = 0; $i < 9; $i++){
$saudiId .= random_int(0,9);
}
} while(validateSaudiId($saudiId) === false);
return (int) $saudiId;
}
Validate the ID
Note: we convert to string so that we can access the numbers based on their index.
function validateSaudiId(string $id) : bool
{
$sum = 0;
for($i = 0; $i < 9; $i++){
if( $i % 2 ){
// Even number
$sum += $id[$i];
}
else{
//Odd number
$increment = $id[$i] * 2;
while($increment > 9){
$increment = (string) $increment;
$increment = $increment[0] + $increment[1];
}
$sum += $increment;
}
}
$sum = (string) $sum;
return ($sum[1] == $id[9] || $id[9] == (10 - $sum[1])) ? true : false;
}
Example use
for($i = 0; $i < 10; $i++) var_dump(getRandomSaudiId());
/*
Output:
int(2933617506)
int(2409806096)
int(1072585118)
int(2891306413)
int(1810304558)
int(2591965856)
int(1363032527)
int(1031823269)
int(1265954048)
int(2498099472)
int(1134172537)
*/
I am attempting to create a generater where the user inputs how many items to generate. For each time, a number from 1 to 100 is generated. Depending on the result, an item is randomly selected from one of three arrays. It should loop as needed and then display the results. I have partial code below as I tried to follow the logic.
<form action='random.php' method='POST' id='random'>
<table class='table table-responsive'>
<tr>
<td>Number of items: </td>
<td><input type='text' name='randitem'></td>
<td><button type="submit"Generate</button>
</td>
</tr>
</table>
<?php
$roll = rand(1, 100);
if $roll < 50
$commonItem = array(citem1, citem2, citem3);
if $roll => 50 and < 95
$uncommonItem = array(uitem1, uitem2, uitem3);
if $roll => 95
$rareItem = array(ritem1, ritem2, ritem3);
?>
Here's an idea, where you can randomly choose an item from each array based on which array to choose from (also random, per your sample code):
<?php
$commonItems = array('citem1', 'citem2', 'citem3');
$uncommonItems = array('uitem1', 'uitem2', 'uitem3');
$rareItems = array('ritem1', 'ritem2', 'ritem3');
$roll = rand(1,100);
if ($roll < 50) {
$size = count($commonItems) - 1;
$index = rand(0,$size);
$item = $commonItems[$index];
} elseif ($roll >= 50 && $roll < 95) {
$size = count($uncommonItems) - 1;
$index = rand(0,$size);
$item = $uncommonItems[$index];
} else {
$size = count($rareItems) - 1;
$index = rand(0,$size);
$item = $rareItems[$index];
}
echo $item;
?>
Here's a refactored version with a function that handles the repetitive functionality in the if statements:
<?php
$commonItems = array('citem1', 'citem2', 'citem3');
$uncommonItems = array('uitem1', 'uitem2', 'uitem3');
$rareItems = array('ritem1', 'ritem2', 'ritem3');
function getItem($itemArray) {
$size = count($itemArray) - 1;
$index = rand(0,$size);
return $itemArray[$index];
}
$roll = rand(1,100);
if ($roll < 50) {
$item = getItem[$commonItems];
} elseif ($roll >= 50 && $roll < 95) {
$item = getItem[$uncommonItems];
} else {
$item = getItem[$rareItems];
}
echo $item;
?>
EDIT: I missed the part about how you input a number of items, so here's that
// Check to see if form was submitted with something in randitem
if (isset($_POST['randitem'])) {
$commonItems = array('citem1', 'citem2', 'citem3');
$uncommonItems = array('uitem1', 'uitem2', 'uitem3');
$rareItems = array('ritem1', 'ritem2', 'ritem3');
function getItem($itemArray) {
$size = count($itemArray) - 1;
$index = rand(0,$size);
return $itemArray[$index];
}
// loop number of times set in form
foreach ($i = 0; $i < $_POST['randitem']; $i++) {
$roll = rand(1,100);
if ($roll < 50) {
$item = getItem[$commonItems];
} elseif ($roll >= 50 && $roll < 95) {
$item = getItem[$uncommonItems];
} else {
$item = getItem[$rareItems];
}
echo $item . "<br>"; // will print each item on its own line
}
}
?>
Note: this will do nothing if the form is submitted without a number, so consider changing the input type to "number" or doing some other validation to the form to ensure that only a number is sent to the PHP
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++;
}
?>
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;
}