Using while loop to print 10-20 odd numbers on the screen, with <-> (exapmle 11-13-15-17-19, <-> not after 19).How to take the last number so as not to put a -. Thank you.
<?php
$x = 10;
while($x < 20){
$x++;
if($x % 2){
echo $x. "-";
}
}
You can push the odd values to an array and after the loop you can convert the array to a string with the implode (https://www.php.net/manual/en/function.implode.php) function.
$x = 10;
$arr = [];
while($x<20){
$x++;
if ($x%2){
$arr[] = $x;
}
}
echo implode(",", $arr);
// output will be a comma seperated string
without (helper)array
You can use rtrim() (https://www.php.net/manual/de/function.rtrim.php) funktion.
$str = "1,2,3,";
echo rtrim($str,",");
As mentioned in the comments, have a boolean variable say firstTime. If this is true, don't prepend a hyphen, else if it is false, prepend it with a hyphen.
<?php
$x = 10;
$firstTime = true;
while($x < 20){
$x++;
if($x % 2){
echo ($firstTime ? "" : "-") . $x;
$firstTime = false;
}
}
Turn the limit number into a variable and use a ternary operator to print out a dash only if $x + 1 < $limit
https://paiza.io/projects/EDj6-u-FAcYxYoR7ON_cvg
<?php
$x = 10;
$y = 20;
while($x < $y){
$x++;
if($x % 2){
echo ($x + 1 === $y) ? $x : $x. "-";
}
}
?>
Simple approach
Imagine you are printing a list of numbers from 10 to 20. If it's an even number, print the "-" symbol and if it's odd number, print the number.
<?php
$start = 10;
$end = 20;
while($start<$end)
{
$n=$start;
if($n>10)
echo ($n%2==0)?"-":$n; //the gist is here
$start++;
}
Related
This is the code I have. It currently works as is, However I'm experimenting with loops and want to see it can be done with a while loop and how it would be done. With this code I can take 2 input numbers and display them, then point out all odds, add all evens, and add all the squares of the odds.
define ("B","<br/>");
$firstNum = $_POST["firstNum"];
$secondNum = $_POST["secondNum"];
if ($firstNum < $secondNum)
{
$firstNum = true;
}
elseif ($firstNum >= $secondNum)
{
$firstNum = "You didn't listen, dumb dumb!".'<br/>GO BACK';
}
echo "First Number: ".$firstNum."<br/>"."Second Number: ".$secondNum;
echo B;
echo B;
$numbers = array();
$numbers = range($firstNum, $secondNum);
$length = count($numbers);
$odds = array();
$sumSqOdds = 0;
$sumEven = 0;
$j = 0;
for ($x = 0; $x < $length; $x++)
{
if (($numbers[$x] % 2) == 1)
{
$odds[$j] = $numbers[$x];
$sumSqOdds = $sumSqOdds + pow ($numbers[$x], 2);
$j++;
}
else
{
$sumEven = $sumEven + $numbers[$x];
}
}
$x = 0;
$y = 0;
printf("The odd numbers between your integers are: ");
for ($x = 0; $x < $j; $x++)
{
echo $odds[$x];
echo ' ';
$y++;
if (($y % 10) == 0)
{
echo B;
}
}
echo B;
echo B;
printf("The sum of all even numbers between your integers is: ".$sumEven);
echo B;
echo B;
printf("The sum of the square of the odd numbers between your integers is: ".$sumSqOdds);
Here is my while loop but it seems to be infinite...
$numW = array ();
$numW = range ($firstNum, $secondNum);
$lengthW = count ($numW);
$oddsW = array ();
$sumSqOddsW = 0;
$sumEvenW = 0;
$j = 0;
$x = 0;
while ($x < $lengthW)
{
if (($numW[$x] % 2) == 1)
{
$oddsW[$j] = $numW[$x];
$sumSqOddsW = $sumSqOddsW + pow ($numW[$x], 2);
$x++;
$j++;
}
else
{
$sumEvenW = $sumEvenW + $numW[$x];
}
}
$x = 0;
$y = 0;
printf ("The odd numbers between your integers are: ");
while ($x < $j)
{
$x++;
echo $oddsW[$x];
echo "nbsp;";
$y++;
if (($y % 10) == 0)
{
echo B;
}
}
Equivalent loops:
for ($i = 0; $i < 10; $i++) {
echo $i;
}
$i = 0;
while ($i < 10) {
echo $i;
$i++;
}
For a loop to ever finish it has to change one of the two evaluating variables. So either $x, or $lengthW would have to change during iteration. You made an if statment, in the first case you define that X increases by 1, but in the else case you do not change any variable that then has an effect on either $x, or $lengthW
Nor is there any check that sees if the else state has been reached and to catch that by either changing $x or $lengthW in a later iteration.
As such there's an infinite loop as soon as you reach the else case.
The if statement uses the same $x value as the last iteration checking the same position of the $numW, as such nothing has changed since the last iteration and you'll hit the else again, and again, and so on.
while ($x < $lengthW)
{
if (($numW[$x] % 2) == 1)
{
$oddsW[$j] = $numW[$x];
$sumSqOddsW = $sumSqOddsW + pow ($numW[$x], 2);
$x++; //$x is increased by one, and as such, the loop will progress.
// remove this $x++ if you place it outside the if else statement.
$j++;
}
else // reached when ($numW[$x] %2) != 1
{
$sumEvenW = $sumEvenW + $numW[$x];
// No changes to $x or $lengthW as such you'll hit the else again
// this could be solved by either adding $x++; here.
}
// or by adding $x++; here
// (if you do add it here, remove it in the if case above,
// or you risk increasing it by 2 every iteration
}
I want to make a script in PHP which displays the numbers and a hyphen between the numbers. It should look like this:
1-2-3-4-5-6-7-8-9-10
I have the following script right now, but the problem is it displays a hyphen at the end of the numbers:
$x = 1;
$h = 1;
while($x <= 10) {
echo "$x";
$x++;
if($h < $x){
echo "-";
$h++;
}
}
Thanks in advance :)
There is simpler way to do this work. Use range() to create array contain numbers and use implode() to join target array with string.
echo implode("-", range(1, 10));
See result in demo
Insert the hypen before the number, except for the first number.
$x = 1;
while($x <= 10) {
if($x > 1)
echo '-';
echo $x;
$x++;
}
You can use temp string
<?php
$x = 1;
$str ='';
while($x <= 10) {
if ($str == '') {
$str = $x;
} else {
$str = $str .'-'.$x;
}
}
echo $str;
?>
This should solve the problem (I don't know why you use the h variable):
<?php
$x = 1;
$result="";
while($x <= 10) {
$result.=$x."-";
}
echo substr($result, 0,-1);
?>
or use the implode function
I'd like to add even numbers to an array and then echo it out, here's my code but it just shows array() when I print...what am i doing wrong?
<?php
$x =88;
$numbers = array();
while ($x % 2 == 0 && $x <= 99) {
$numbers[] = "$x";
$x++;
}
print_r($numbers);
?>
You should move the "evenness" test from the while loop, and move it to a conditional within the while loop:
<?php
$x = 88;
$numbers = array();
while ($x <= 99) {
if ($x % 2 == 0) {
$numbers[] = $x;
}
$x++;
}
print_r($numbers);
?>
As you have currently written the while loop, it ends if the number is not even. You should also remove the quotes from $x when you add to the $numbers array.
I have the following loop that combines two arrays and displays the results in an ordered list:
$list1 = array("make","break","buy");
$list2 = array("home","car","bike");
echo "<ol>";
for($a=0; $a<3; $a++){
for($b=0; $b<3; $b++){
echo "<li".($list1[$a].$list2[$b])."</li>";
}
}
echo "</ol>";
The actual arrays that I have include about 1500 words each, so the list is more than 2 Million combinations long.
Is there a way to display the results with pagination, without generating the entire result set in advance?
For example 500 items per page?
FYI, I don't necessarily need to display the results in an ordered list, if that's going to mess up the pagination.
First, you'll need to be able to start looping from any position in the arrays.
Of course you can use for loops, but I think while loops fit better here.
$length1 = count($list1);
$length2 = count($list2);
//now indexes are initialized to variable values
$a = $var1; //start position $var1 is an integer variable between 0 and ($length1 - 1)
$b = $var2; //start position $var2 is an integer variable between 0 and ($length2 - 1)
while ($a < $length1) {
while ($b < $length2) {
echo '<li>', $list1[$a], ' ', $list2[$b], '</li>';
$b++;
}
$b = 0; //reset inner loop each time it ends
$a++;
}
Next, we need a way to stop both loops if the maximum number of results per page ($limit) is reached before the end of the combinations.
$length1 = count($list1);
$length2 = count($list2);
$a = $var1;
$b = $var2;
$counter = 0;
while ($a < $length1) {
while ($b < $length2) {
echo '<li>', $list1[$a], ' ', $list2[$b], '</li>';
$counter++;
if($counter === $limit) break 2;
$b++;
}
$b = 0;
$a++;
}
Finally, we must find the correct values for $var1 and $var2 above, based on the current $page (starting from page 1) and $limit. This is plain arithmetics that I won't explain here.
Putting it all together:
$length1 = count($list1);
$length2 = count($list2);
$offset = $limit * ($page - 1);
$a = (int)($offset / $length2);
$b = $offset % $length2;
$counter = 0;
while ($a < $length1) {
while ($b < $length2) {
echo '<li>', $list1[$a], ' ', $list2[$b], '</li>';
$counter++;
if($counter === $limit) break 2;
$b++;
}
$b = 0;
$a++;
}
I have a two variable one is string contains number and another one is number,
I want increase the numeric part of string upto second number.
$n ='sh500';
$c = 3;
for($i=$n;$i<$c;$i++)
echo $i.'<br>';
I want output like:
sh500
sh501
sh502
Use $n++ where $n = 'sh500'. It works.
$n ='sh500';
$c = 3;
for($i = 0;$i < $c;$i++) {
echo $n++.'<br>';
}
Will output
sh500 <br>
sh501 <br>
sh502 <br>
It even works when ending with a alphanumeric character, because php converts it to the ASCII value of the character and adds one so a will become b and so on. But that's out of the scope of the question :)
$x="sh500";
$x = substr($x,0,2) . (substr($x,2) + 1);
echo $x;
echoes sh501 (works for any string having a number from 3rd character)
$n = 'sh';
for($i = 500; $i < 503; $i++) {
echo "$n$i\n";
}
$n="sh50";
for($i=0;$i<10;$i++){
$j=$n.$i;
echo $j."<br>";
}
it echo:
sh500
sh501
sh502
sh503
sh504
sh505
sh506
sh507
sh508
sh509
$n = 'sh500';
$c = 3;
$sh = substr($n,0,2); // will be "sh"
$number = substr($n,2,5) + 1; // will be "500"
for($i = $number; $i < 504; $i++) {
echo $sh.$i."\n";
}
Live demo: Here
if it is always a string of length 2 else use preg_match to find the first occurrence of a number.
http://www.php.net/manual/en/function.preg-match.php
$number = intval(substr($n, 2));
$number++;
echo substr($n, 0, 2) . $number;
$x = "sh500";
$s = substr($x, 0, 2);
$n = substr($x, 2);
$c = 3;
for ($i = $n; $i < ($n + $c); $i++)
{
echo $s.$i.'<br>';
}
OR another simple way is...
$n ='sh500';
$c = 3;
for ($i = 0; $i < $c; $i++) {
echo $n++."<br>";
}
Output
sh500
sh501
sh502