PHP.. How to loop by some selected number? - php

I need a output like this
Number 5
Number 4
Number 9
Number 3
Number 8
Number 10
And so on (There are more like this)
I used this code
<?php
for ($i = 0; $i <= 10 ; $i++) {
if ($i == 5 || $i == 4 || $i == 9) { //And so on Like this
echo "$i<br>";
}
}
?>
But the main problem is output is showing the number serially.
//It shows
Number 3
Number 4
Number 5
Number 8
Number 9
Number 10
//But I need
Number 5
Number 4
Number 9
Number 3
Number 8
Number 10
And this takes much time to code. And it not looks so good. Sure there is a easy way out!
I am expecting something like this -
//Surely this is not right. It's just an idea.
<?php
$x = 5,4,9,3,8,10;
for ($i = 0; $i = $x; $i++) {
echo "$i<br>";
}
?>

Take this
$x = array(5,4,9,3,8,10);
foreach ($x as $i) {
echo "Number $i<br>";
}
but please, learn the basics of PHP if you really want to code in php.

JustOnUnderMillions's answer is corrent - You can even have access to key & value like this
$x = array(
"num1" => 1,
"num2" => 2,
...
...
);
foreach($x as $key => $value){
echo $key . " : " . $value . "<br>";
}

Related

Number counter game

Im trying to make a random number counter game that uses a for loop to print out 6 random numbers 1 - 6. I want to make it so the code can say how many times the number 6 shows in the loop.
At the moment I have the code it prints out for a loop of 6 random numbers but it only counts the numbers printed out.
For example
Welcome to the Dice Game!
How many sixes will you roll?
4 2 4 6 4 6
You rolled 2 six(es)!
<?php
echo"<h1>Welcome to the guess game thing guess how many 6s!</h1>";
$counter = 0;
for ($i=0; $i <=6;$i++) {
$randomNum = rand(1,6);
if ($randomNum <= 6) {
echo "<br> $randomNum";
$counter++;
}
else
{
echo"$randomNum <br>";
}
}
echo"<br>You rolled $counter sixes";
Some minor changes but you were almost there. Being consistent with your line breaks and verifying you check specifically for 6
$numberToMatch = 6;
for ($i = 0; $i <= 6; $i++) {
$randomNum = rand(1,6);
if ($randomNum == $numberToMatch) {
$counter++;
}
echo "$randomNum <br>";
}
You can do it like this:
$num = $_POST["num"];
for ($i=0; $i <=100;$i++) {
$randomNum = rand(1,10);
if ($randomNum == $num) {
echo $randomNum;
break;
}
echo $randomNum;
}
echo"<h2> there are $i</h2>";

How to print odd/even series without if-statement

I'm writing program to list odd/even series from n elements (1,2,...n) using if-statement.
For example,
n = 1
Odd Series
1
3
5
7
9
Even Series
0
2
4
6
8
If any possible to print odd/even series without if-statement.
You can just use range with a step of 2, starting with either 0 or 1 as required:
echo "Odd Series\n";
foreach (range(1, 9, 2) as $v) echo "$v ";
echo "Even Series\n";
foreach (range(0, 9, 2) as $v) echo "$v ";
Output:
Odd Series
1 3 5 7 9
Even Series
0 2 4 6 8
Demo on 3v4l.org
Yes. This is possible. We can list odd or even series without if-condition.
We use Increment operator insteed of if-condition.
Sample code is,
<?php
echo "Odd Series";
echo "<pre>";
for ($i=0; $i < 10; $i++) {
echo ++$i;
}
echo "Even Series";
echo "<pre>";
for ($i=0; $i < 10; $i++) {
echo $i++;
}
?>
Sample output is here,
Odd Series
1
3
5
7
9
Even Series
0
2
4
6
8
We could try using a ternary expression in lieu of an if statement:
// even series
for ($i = 0; $i < 10; $i++) {
echo $i % 2 == 0 ? $i : "\n";
}
Another possibility is to just iterate the for loop by steps of 2:
for ($i = 0; $i < 10; $i=$i+2) {
echo $i . "\n";
}
Using arrays, you can create the range with range(), and use array_filter() to pluck the odd or even values using bit-operators.
$n = 8;
$series = range(1, $n);
$odd = array_filter($series, function($value) { return $value & 1; });
$even = array_filter($series, function($value) { return !($value & 1); });
var_dump($odd, $even);
Then its just a matter of looping the arrays $odd and $even.
echo "Odd values: \n";
foreach ($odd as $v) {
echo $v."\n";
}
echo "Even values: \n";
foreach ($even as $v) {
echo $v."\n";
}
Live demo at https://3v4l.org/J9Dio

Can someone help me return a value?

I have created a loop which returns a random number between two values. Cool.
But now I want the script to return the following value too: The number of unique numbers between two similar numbers.
Example:
4
5
8
22
45
3
85
44
4
55
15
23
As you see there is a double which is the four and there are 7 numbers inbetween. So I would like the script to echo these numbers two so in this case it should echo 7 but if there are more doubles in the list it should echo all the numbers between certain doubles.
This is what I have:
for ($x = 0; $x <= 100; $x++) {
$min=0;
$max=50;
echo rand($min,$max);
echo "<br>";
}
Can someone help me or guide me? I'm learning :)
Thanks!
So You need to seperate script for three parts:
getting randoms and save them to array (name it 'result'),
analyze them,
print (echo) results
Simply - instead of printing every step of loop, save them to array(), exit loop, analyze every item with other, example:
take i element of list
check is i+j element is the same
if is it the same - save j-i to second array() (name it 'ranges')
And after this, print two arrays (named by me as 'result' and 'ranges')
UPDATE:
Here's solution, hope You enjoy:
$result = array(); #variable is set as array object
$ranges = array(); #same
# 1st part - collecting random numbers
for ($x = 0; $x < 20; $x++)
{
$min=0;
$max=50;
$result[] = rand($min,$max); #here's putting random number to array
}
$result_size = count($result); #variable which is containg size of $result array
# 2nd part - getting ranges between values
for ($i = 0; $i < $result_size; $i++)
{
for ($j = 0; $j < $result_size; $j++)
{
if($i == $j) continue; # we don't want to compare numbers with itself,so miss it and continue
else if($result[$i] == $result[$j])
{
$range = $i - $j; # get range beetwen numbers
if($range > 0 ) # this is for miss double results like 14 and -14 for same comparing
{
$ranges[$result[$i]] = $range;
}
}
}
}
#3rd part - priting results
echo("RANDOM NUMBERS:<br>");
foreach($result as $number)
{
echo ("$number ");
}
echo("<br><br>RANGES BETWEEN SAME VALUES:<br>");
foreach($ranges as $number => $range)
{
echo ("For numbers: $number range is: $range<br>");
}
Here's sample of echo ($x is set as 20):
RANDOM NUMBERS:
6 40 6 29 43 32 17 44 48 21 40 2 33 47 42 3 22 26 39 46
RANGES BETWEEN SAME VALUES:
For numbers: 6 range is: 2
For numbers: 40 range is: 9
Here is your fish:
Put the rand into an array $list = array(); and $list[] = rand($min,$max); then process the array with two for loops.
$min=0;
$max=50;
$list = array();
for ($x = 0; $x <= 100; ++$x) {
$list[] = rand($min,$max);
}
print "<pre>";print_r($list);print "</pre>";
$ranges = array();
$count = count($list);
for ($i = 0; $i < $count; ++$i) {
$a = $list[$i];
for ($j = $i+1; $j < $count; ++$j) {
$b = $list[$j];
if($a == $b) {
$ranges[] = $j-$i;
}
}
}
print "<pre>";print_r($ranges);print "</pre>";

I am facing a small bump printing number pyramids , still a newbie to php and programming

What i want to print is
1
3 5
7 9 11
With my current code , that is ...
<?php
function Odd($limit='20'){
$c = 1;
while($c <= $limit){
if ($c % 2!=0){
echo $c ;
echo "<br/>";
}
$c++ ;
}
}
Print Odd();
?>
i am getting
1
3
5
7
9
11
Can someone please guide me the right way ?
Aaah ... ok.^^ Now i got it.
Its pretty easy: You need another variable which counts up and one which limits the breakposition. Looks like this:
<?php
function Odd($limit='40'){
$c = 1;
$count = 0;
$break = 1;
while($c <= $limit){
if ($c % 2!=0){
echo $c . " ";
$count++;
if($count === $break) {
echo "<br/>";
$break++;
$count = 0;
}
}
$c++ ;
}
}
Print Odd();
?>
Output till 40:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
31 33 35 37 39
Edit: Code for your new request:
<?php
function Odd($limit='40'){
$c = 1;
$count = 0;
$break = 1;
while($c <= $limit){
echo $c . " ";
$count++;
if($count === $break) {
echo "<br/>";
$break++;
$count = 0;
}
$c++ ;
}
}
Print Odd();
?>
So if I understand correctly you want to output something like that:
1
3 5
7 9 11
13 15 17 19
Here is my solution:
function Odd($limit='20'){
$c = 1;$some_array = array();
while($c <= $limit){
if ($c % 2!=0){
$some_array[]=$c;
}
$c++ ;
}
return $some_array;
}
$array = Odd();
$nr =0;
$j=1;
foreach ($array as $key => $value) {
echo $value.' ';$nr++;
if($nr==$j){
echo '<br />';
$nr=0;
$j++;
}
}
Hope this helps!
From your question it Seems you are really new to programming so before writing any program first of all observe the question properly:
For example for the question above it is clear that is an triangle of odd numbers.
now the number of odd numbers on each row is equal to the row
i.e 1st row contains 1 number ,2nd contains 2 and it continues...
Now what we do is take an variable to count the no of rows say $row and the other will be $limit .
<?php
function odd($limit){
$row=1;
$current_number=1;
while($current_number<=$limit){
for($i=1;$i<=$row;$i++){
echo $current_number." ";
$current_number=$current_number+2;//incrementing numbers by 2 if you want to increment by 1 i.e print all numbers replace 2 by 1
}
$row++;
echo "<br/>";//for new line
}
}
To run above function you need to call it and pass the value of $limit.To do it just type anywhere outside of this function.
odd(20);
Watch this running here:

How do I distribute values of an array in three columns?

I need this output..
1 3 5
2 4 6
I want to use array function like array(1,2,3,4,5,6). If I edit this array like array(1,2,3), it means the output need to show like
1 2 3
The concept is maximum 3 column only. If we give array(1,2,3,4,5), it means the output should be
1 3 5
2 4
Suppose we will give array(1,2,3,4,5,6,7,8,9), then it means output is
1 4 7
2 5 8
3 6 9
that is, maximum 3 column only. Depends upon the the given input, the rows will be created with 3 columns.
Is this possible with PHP? I am doing small Research & Development in array functions. I think this is possible. Will you help me?
For more info:
* input: array(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
* output:
1 6 11
2 7 12
3 8 13
4 9 14
5 10
You can do a loop that will automatically insert a new line on each three elements:
$values = array(1,1,1,1,1);
foreach($values as $i => $value) {
printf('%-4d', $value);
if($i % 3 === 2) echo "\n";
}
EDIT: Since you added more information, here's what you want:
$values = array(1,2,3,4,5);
for($line = 0; $line < 2; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < count($values); $i+=2) {
printf('%-4d', $values[$i]);
}
}
And if you want to bundle all that in a function:
function print_values_table($array, $lines = 3, $format = "%-4d") {
$values = array_values($array);
$count = count($values);
for($line = 0; $line < $lines; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < $count; $i += $lines) {
printf($format, $values[$i]);
}
}
}
EDIT 2: Here is a modified version which will limit the numbers of columns to 3.
function print_values_table($array, $maxCols = 3, $format = "%-4d") {
$values = array_values($array);
$count = count($values);
$lines = ceil($count / $maxCols);
for($line = 0; $line < $lines; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < $count; $i += $lines) {
printf($format, $values[$i]);
}
}
}
So, the following:
$values = range(1,25);
print_array_table($values);
Will output this:
1 10 19
2 11 20
3 12 21
4 13 22
5 14 23
6 15 24
7 16 25
8 17
9 18
One solution is to cut the array into chunks, representing the columns, and then print the values in row order:
$cols = array_chunk($arr, ceil(count($arr)/3));
for ($i=0, $n=count($cols[0]); $i<$n; $i++) {
echo $cols[0][$i];
if (isset($cols[1][$i])) echo $cols[1][$i];
if (isset($cols[2][$i])) echo $cols[2][$i];
}
If you don’t want to split your array, you can also do it directly:
for ($c=0, $n=count($arr), $m=ceil($n/3); $c<$m; $c++) {
echo $arr[$c];
for ($r=$m; $r<$n; $r+=$m) {
echo $arr[$c+$r];
}
}
$a = array(1,2,3,4,5);
"{$a[0]} {$a[1]} {$a[2]}\n{$a[3]} {$a[4]}";
or
$a = array(1,2,3,4,5);
"{$a[0]} {$a[1]} {$a[2]}".PHP_EOL."{$a[3]} {$a[4]}";
or
$a = array(1,2,3,4,5);
$second_row_start = 3; // change to vary length of rows
foreach( $a as $index => $value) {
if($index == $second_row_start) echo PHP_EOL;
echo "$value ";
}
or, perhaps if you want a longer array split into columns of 3?
$a = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
$row_length = 3; // change to vary length of rows
foreach( $a as $index => $value) {
if($index%$row_length == 0) echo PHP_EOL;
echo "$value ";
}
which gives
1 2 3
4 5 6
7 8 9
10 11 12
13
one solution is :
your array has N elements, and you want 3 columns, so you can get the value of each cell with $myarray[ column_index + (N/3) + line_index ] (with one or two loops for columns and lines, at least for lines)
I hope this will help you
Bye
Here's something I whipped up. I'm pretty sure this could be more easily accomplished if you were using HTML lists, I've assumed you can't use them.
$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15, 16);
$max = count($arr);
$cols = 3;
$block = ceil($max / $cols);
for ($i = 0; $i < $block ; $i++) {
echo $arr[$i] . ' ';
for ($j = 1; $j < $cols; $j++) {
$nexKey = $i + $block * $j;
if (!isset($arr[$nexKey])) break;
echo $arr[$nexKey] . ' ';
}
echo '<br>';
}
NOTE : You can easily refactor the code inside the loop that uses $nexkey variable by making it into a loop itself so that it works for any number of columns. I've hardcoded it.
Uses loops now.

Categories