everything good ? I'm having a problem where I'm a beginner in php and would need help.
the user must enter an initial number, for example: 1
<input type="number" name"number" id="number">
where he then informs the quantity: 30
<input type="number" name"qtd" id="qtd">
in case I would like to make a loop in which every 10 repetitions are incremented a new number.
the result of the above example would be:
1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3, 3,3,3,3,3,3
its possible ?
here look my code that i was trying , but i couldn't find a logical way .
<?php
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
//echo $_POST['sequencial'];
for ($i = 1; $i <= 100; $i++){
echo $i. "<br>";
}
?>
You can do it that way. It works very nice.
$str =array();
for($i=0;$i<10;$i++)
{
for($j=0;$j<10;$j++){
$str[]=$i;
}
$j=0;
}
echo implode($str,',');
Related
I am trying to be able to make a loop that lets me place stars on a website, to show a rating (1 to 5) on the website, that you can put down with fields. However, I do not know how to convert the field correctly.
I am using WordPress with Custom Field types, this is were I define the variable.
I have a variable that I get from somewhere else, and I have tried the following two ways:
<?php
$star = intval(the_field('rating'));
for ($i=0; $i < $star; $i++){
intval(the_field('rating'));
}
?>
and the second one:
<?php
$star = number_format(the_field('rating');
for ($i=0; $i < $star; $i++){
number_format(the_field('rating'));
}
?>
Thank you very much for you help in advance.
First the_field echos the value, you need get_field to return the value. Then just repeat whatever string you're using to display a star or empty star:
$stars = get_field('rating');
echo str_repeat('*', $stars) . str_repeat('O', 5-$stars);
With a loop just check if your counter is less than or equal to the star rating:
$stars = get_field('rating');
for ($i=1; $i <= 5; $i++){
echo ($i <= $stars) ? "*" : "O";
}
What I am doing:
ob_implicit_flush(true);
ob_end_flush();
$i = 0;
foreach($offers as $key => $value){
i++;
echo 'number: ' . $i;
}
In page it returns like this:
number:1number:2number:3 etc....
What I want to do is make it display only the current number:
number:1, then in second loop change only 1 to 2... so it should display number:2 only... and like that...
Is it possible with only php? I have little skill in javascript, jquery.. All help welcome.
I'm pretty much a PHP beginner, although I can copy and paste like no one's business and generally I'm able to pick it apart and figure out what's going on :) This is my first post here, but I've gotten lots of help from other answers, so thanks for all the past and hopefully future help!
Basically what I'm trying to replicate here is an equestrian show jumping event, in which each knockdown of a pole equals four faults, and time faults are given for going over the time allowed. All horses who jump clear, that is, with zero faults, go on to a jump-off round, where they may or may not incur faults.
My current issue is using for and foreach loops to advance two different arrays. The problem I'm having is that if I get one array working, the other stops. One of the arrays needs to be shuffled, the other needs to be sorted in numerical order. Basically it's a randomizer which will take a series of horses and give them placings and then assign a weight random number of faults (it's for a horse game, nerdy, I know). Here is the code I'm working with:
index.php
<form action="classes.php" method="post">
How many classes do you wish to randomize?<br />
<input type="text" name="number"><br />
<input type="submit" /><br />
</form>
classes.php
<form action="action.php" method="post">
<?php
$number = $_POST['number']; //This is the desired value of Looping
echo '<input type="hidden" value="' . $number . '" name="number">';
$i = 1; //First we set the count to be zero
while ($i<=$number) {
echo '
Class: <input type="text" name="class' . $i . '"><br />
<textarea cols="100" rows="20" name="entries' . $i . '"></textarea><br />
<br />';
$i++; //Increase the value of the count by 1
};
?>
<input type="submit" /><br />
</form>
action.php
$number = $_POST['number']; //This is the desired value of Looping
function array_rand_weighted($values) {
$r = mt_rand(1, array_sum($values));
foreach ($values as $item => $weight) {
if ($r <= $weight) return $item;
$r -= $weight;
}
}
for ($i=1; $i<=$number; $i++) {
$class[$i] = $_POST['class'.$i];
//trim off excess whitespace off the whole
$text[$i] = trim($_POST['entries'.$i]);
//explode all separate lines into an array
$textAr[$i] = explode("\n", $text[$i]);
//trim all lines contained in the array.
$textAr[$i] = array_filter($textAr[$i], 'trim');
//shuffle the results
shuffle($textAr[$i]);
//add faults
//loop through the lines
echo '<div id="output">
[b]' . $class[$i] . '[/b]<br />';
foreach($textAr[$i] as $key[$i]=>$line[$i]){
$knockdowns = array( 0 => 20, 1 => 25, 2 => 30, 3 => 10, 4 => 8, 5 => 7); // knockdowns
$knockdowns = array_rand_weighted($knockdowns)*4;
$timefaults = array( 0 => 75, 1 => 10, 2 => 10, 3 => 5); // time faults
$timefaults = array_rand_weighted($timefaults);
$faultsadded = $knockdowns + $timefaults;
$faults[$i] = $faultsadded;
}
asort($faults);
foreach($textAr[$i] as $key[$i]=>$line[$i]){
echo $key + 1,". " . $line . " (" . $faults[$i] . " Faults)<br />";
}
echo '</div>';
}
At present, this code is producing the randomized results I need, but not the faults. When I am able to get it to produce the full set of faults, the list of random horses stops functioning. I have never been able to get the faults to sort in order of value (0-20+). I found another answer using array_combine, and thought maybe to use this, but I need the key (I think- maybe I don't really?).
If you want to see it in action, here is the link: http://www.eecreates.com/randomizer/dhjc%20randomizer/ it's a multi-class randomizer, so on the first page you put the number of classes you want to randomize, then the next page you input the class name and horses entered.
The final product I'm going for would look something like this:
Show Jumping Class
penny (0 Faults | 0 Faults)
sheldon (0 Faults | 4 Faults)
raj (4 Faults)
leonard (5 Faults)
howard (8 Faults)
amy farrah fowler (8 Faults)
bernadette (9 Faults)
I'd also like for it to show a second set of faults for those horses who have zero to begin with, but of course one thing at a time. :) Thank you!
Totally new answer. index.php remains unchanged. I've reworked the code in classes.php to use named arrays. This simplifies the processing in action.php. See below for notes on that. The code here will need to be wrapped in a suitable HTML page layout.
Note that although the code changes are extensive I have minimised the changes to the data structures. This is not necessarily the way I'd handle the data structures if I was starting from scratch.
classes.php
<form action="action.php" method="post">
<?php
$number = $_POST['number']; //This is the desired value of Looping
echo '<input type="hidden" value="' . $number . '" name="number">';
$i = 1; //First we set the count to be zero
while ($i<=$number) {
echo '
Class: <input type="text" name="class[]"><br />
<textarea cols="100" rows="20" name="entries[]"></textarea><br />
<br />';
$i++; //Increase the value of the count by 1
};
?>
<input type="submit" /><br />
</form>
action.php
I've moved the weighted random faults code into its own function. Since the data coming from classes.php is now already in array form I've simplified the processing, and separated it from the output. Once the processing is done and the number of faults generated, a pair of nested loops generates the output by class and entrant.
<?php
function array_rand_weighted($values) {
$r = mt_rand(1, array_sum($values));
foreach ($values as $item => $weight) {
if ($r <= $weight) return $item;
$r -= $weight;
}
}
// generate a random value for faults and return in sorted order, ascending.
function generateFaults($numEntries) {
$faults = array();
while ($numEntries) {
$knockdowns = array( 0 => 20, 1 => 25, 2 => 30, 3 => 10, 4 => 8, 5 => 7); // knockdowns
$knockdowns = array_rand_weighted($knockdowns)*4;
$timefaults = array( 0 => 75, 1 => 10, 2 => 10, 3 => 5); // time faults
$timefaults = array_rand_weighted($timefaults);
$faults[] = $knockdowns + $timefaults;
$numEntries--;
}
// echo nl2br(print_r($faults, true));
sort($faults);
return $faults;
}
$textAr = array();
$faults = array();
// Iterate over the entries array, extracting the names of our entrants.
foreach ( $_POST['entries'] as $entries) {
//explode all separate lines into an array
$tempEntries = explode("\n", $entries);
//shuffle the results
shuffle($tempEntries);
//trim all lines contained in the array and assign to next entry in $textAr
$textAr[] = array_filter($tempEntries, 'trim');
//add faults
$faults[] = generateFaults(count($tempEntries));
}
//loop through the lines
// echo nl2br(print_r($faults, true));
for ($i=0; $i<count($_POST['class']); $i++) {
echo '<div id="output">
<b>' . $_POST['class'][$i] . '</b><br />';
for($j = 0; $j<count($textAr[$i]); $j++) {
echo $j + 1,". " . $textAr[$i][$j] . " (" . $faults[$i][$j] . " Faults)<br />";
}
echo '</div>';
}
?>
Footnote:
I need help creating PHP code to echo and run a function only 30% of the time.
Currently I have code below but it doesn't seem to work.
if (mt_rand(1, 3) == 2)
{
echo '';
theFunctionIWantCalled();
}
Are you trying to echo what the function returns? That would be
if(mt_rand(1,100) <= 30)
{
echo function();
}
What you currently have echoes a blank statement, then executes a function. I also changed the random statement. Since this is only pseudo-random and not true randomness, more options will give you a better chance of hitting it 30% of the time.
If you intended to echo a blank statement, then execute a function,
if(mt_rand(1,100) <= 30)
{
echo '';
function();
}
would be correct. Once again, I've changed the if-statement to make it more evenly distributed. To help insure a more even distribution, you could even do
if(mt_rand(1,10000) <= 3000)
since we aren't dealing with true randomness here. It's entirely possible that the algorithm is choosing one number more than others. As was mentioned in the comments of this question, since the algorithm is random, it could be choosing the same number over, and over, and over again. However, in practice, having more numbers to choose from will most likely result in an even distribution. Having only 3 numbers to choose from can skew the results.
Since you are using rand you can't guarantee it will be called 30% of the time. Where you could instead use modulus which will effectively give you 1/3 of the time, not sure how important this is for you but...
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
Since modulus does not work with floats you can use fmod, this code should be fairly close you can substitute the total iterations and percent...
$total = 50;
$percent = 0.50;
$calls = $total * $percent;
$interval = $total / $calls;
$called = 0;
$notcalled = 0;
for($i = 0; $i <= $total; $i++){
if(fmod($i, $interval) < 1){
$called++;
echo "Called" . "\n";
}else{
$notcalled++;
echo "Not Called" . "\n";
}
}
echo "Called: " . $called . "\n";
echo "Not Called: " . $notcalled . "\n";
I am working on a project for a friend's website which is suppose to generate completely random phone numbers to be displayed on a "fake" review board. I figured the best way to do with would be for me to to generate out each section separably. So 3-3-4, but no matter what I do, every time there is a 0 in front the code cuts it off. Here's an example of what I mean:
http://www.shiningashes.net/Test.php
yet this is what I have for the code:
<?php
for ($i = 0000; $i <= 9999; $i++) {
echo $i;
echo "<br>";
}
?>
How do I get the 0's to stop being cropped out so the 0's display? 0001, 0021, 0123, etc?
You can use str_pad
for ($i = 0; $i <= 9999; $i++) {
echo str_pad($i, 4, '0', STR_PAD_LEFT);
echo "<br>";
}
You can use printf to format your output:
<?php
for ($i = 0; $i <= 9999; $i++) {
printf("%04d<br>\n",$i);
}
?>
You need to make your variable a string if you want to keep the zeros. That would mean using quotes, and never using numeric operators on it. But since you depend on using ++ on it, I suggest the following hack:
<?php
for ($i = 10000; $i <= 19999; $i++) {
$str=substr ( $i , 0 , 4 );
echo $i;
echo $str;
echo "<br>";
}
?>
You will need to convert your integer to a string when printing it.
<?php
for ($i = 0; $i <= 9999; $i++) {
printf("%04d<br />", $i);
}
?>
Check the documentation for printf/sprintf for more information.
Kind regards,
Stefan