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

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.

Related

Sorting and getting higest values codeigniter

I have a cloumn like token_number in table the values inserted in this row are like
token_number
1
2
3
15
4
5
6
14
7
8
18
10
11
9
etc..
I sort these values
1,2,3,4,5,6,7,8,9,10,11,14,15,18
I want to get the value 11 from this sorted array
ie the highest number with common difference 1
How to get 11 from this array?
Since the array is sorted, you can start from the bottom e loop it backwards:
$arr = // sorted array;
$max = null;
for( $i = count($arr) - 1 ; $i > 0 ; $i++ ){
if($arr[$i] - 1 == $arr[$i-1]){
$max = $arr[$i-1];
break;
}
}
if($max !== null){
echo "founded: " . $max;
}
You can find highest number with command difference as follow.
$arr= array(1,2,3,4,5,6,7,8,9,10,11,14,15,18);
$highestNo = null;
for($i=0 ;$i <= count($arr) - 1 ; $i++ ){
$diff = $arr[$i+1] - $arr[$i]; //check difference of current and next number
if($diff != 1){
$highestNo = $arr[$i];
break;
}
}
echo "Highest number with comman difference is: " . $highestNo;

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

PHP: for loop $i value turns zero if the number is greater

I want to turn the $i variable value to start counting from 1 if the given value is greater than 10:
here is what i am trying to achieve
<?php
$givenValue = 15; //number of x value
for ($i = 1; $i < $givenValue; $i++) {
if ($givenValue > 10){
$i = 1;
}
echo $i."<br>";
}
?>
This is how i want my result to look like
output: 1
output: 2
output: 3
output: 4
output: 5
output: 6
output: 7
output: 8
output: 9
output: 10
output: 1
output: 2
output: 3
output: 4
output: 5
in for loop body
Any help is welcome
You can use modulo calculation to get the result you want.
I also changed your if from $givenvalue to $i as $givenvalue will "always" be 10+.
$givenValue = 15; //number of x value
for ($i = 1; $i <= $givenValue; $i++) {
if ($i > 10){
Echo $i%10 . "\n";
}else{
echo $i . "\n";
}
}
https://3v4l.org/5afc5
Another option, if that is possible for you, is to start at zero and only use modulo calculation and add one to it to get the same result.
This also means I need to stop the loop at <$givenvalue as your original code shows.
$givenValue = 15; //number of x value
for ($i = 0; $i < $givenValue; $i++) {
Echo $i%10+1 . "\n";
}
https://3v4l.org/r0sgA
A method that uses less looping is to add 10 to the loop on each iteration and create the values using range().
Then add them to the array with array_merge, and output with implode.
$givenValue = 47; //number of x value
$breakpoint = 10;
$arr=[];
For($i = $breakpoint; $i< $givenValue;){
// Add new values from 1-$breakpoint in array
$arr = array_merge($arr, range(1,$breakpoint));
$i +=$breakpoint;
}
// Loop will exit before all values been collected
// Add the rest of the values
$arr = array_merge($arr, range(1,$givenValue-($i-10)));
// Echo the values in array
Echo implode("\n", $arr);
https://3v4l.org/jGsO4
Your code can be written like this:
<?php
$givenValue = 15; //number of x value
for ($i = 1; $i <= $givenValue; $i++)
{
if ($i > 10)
{
$i = 1;
$givenValue-=10;
}
echo "output: $i\n";
}
?>
http://sandbox.onlinephpfunctions.com/code/ed34d8dcd12a9a5a866b73338ad1209f55298519
You are resenting the counter, I would expect the behaviour you have. To do what you want add another counter to the mix
$j=1;
$givenValue = 15; //number of x value
for ($i = 1; $i <= $givenValue; $i++) {
if ($j > 10){
$j = 1;
}
echo $j."\n";
++$j;
}
You also had several missing ;
Output:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
If you want to end on 5 you have to do 16 as the $givenValue or change it to <= less than or equal
See it here live
See what I have now, the $i variable counts to the $givenValue then the $j variable counts along side it, but with a range of 1-10 ( resets to 1 after 10 )

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:

Categories