Create line breaks in output based on array index - php

I want to display output like this:
1 2 3 4
5 6 7 8
9 1 2
I've tried this code:
$num = ['1','2','3','4','....'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value) {
echo $value;
if($key >= round($size){
echo "<br>"
}
}
But the output is like this:
1 2 3 4
5
6
7
8
...
Can anyone suggest how to write the loop?

$num= ['1','2','3','4','5','6','7','8','9'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value){
echo $value;
if(($key+1) % 4 == 0){
echo "<br>";
}
}
You can use modulus instead of round. Cool I didn't know about sizeOf! Good to know. Mark this as the right answer pwease if this works!
Another way to do this if you didn't want to write out all the numbers that are in the Num Array is to just push them into an array with a while loop.
$num= [];
$i = 1;
//Set the Num Variable to have as many numbers as you want without having to manually enter them in
while ($i < 100) {
array_push($num, $i);
$i++;
}
//Run the actual code that adds breaks ever 4 lines
$size = sizeof($num) / 4;
foreach ($num as $key => $value){
echo $value;
if(($key+1) % 4 == 0){
echo "<br>";
}
}

Sorry if this answer looks the same as the first answer but I will explain it clearer
To achieve what you want
Step 1: Create a for loop
The loop will start from 1 to it's total size of the array
for ($x = 1; $x <= sizeof($num); $x++){
}
Then inside your loop
you can use ternary for simplicity
This line of code
# if $x variable is equal to limit number which you wanted to break
# $num[$x-1] -> subtract to by 1 because we know array always start at index 0
if ($x % 4 == 0) {
$num[$x-1]."<br>"; #put a break after it
} else {
echo $num[$x-1];
}
is same as this
echo ($x % 4 == 0) ? $num[$x-1]."<br>" : $num[$x-1];
So try this
<?php
$num= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
$size = sizeof($num) / 4;
for ($x = 1; $x <= sizeof($num); $x++){
echo ($x % 4 == 0) ? $num[$x-1]."<br>" : $num[$x-1];
}
DEMO

You can try this:
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 8, 19, 20];
$len = 1;
foreach ($numbers as $number) {
echo $number . ' ';
$len++;
if ($len > 4) {
echo '<br>';
$len = 1;
}
}

Related

i want to count number of even,number of odd in php

I want to count number of even,number of odd.If there 2 even ,i count only one even,If there 2 odd i count
only one number of odd
<?php
$myarray = array(5,5,0,1,2,1,1,6,1);
for ($i = 0; $i < count($myarray); $i++) {
echo "Index ", $i, ", value ", $myarray[$i], ": ";
if ($myarray[$i] % 2 == 0) {
echo "even\n";
}
else {
echo "odd\n";
}
}
?>
input =[5,5,0,1,2,1,1,6,1]
output = 5 :1(total(5) odd one),
1:2 (total(1) odd two)
Use two variables that keep track of your odds and evens when you loop through your array.
$my_array = array( 5, 5, 0, 1, 2, 1, 1, 6, 1 );
$odd = $even = 0;
foreach ( $my_array as $number ) {
$number % 2 == 0 ? $even++ : $odd++;
}
printf( 'Odd: %s | Even: %s', $odd, $even );
<?php
$num = array(23,12,11,9,6,7,4,5,3);
$n=count($num);
$even = 0;
$odd = 0;
for( $i = 0 ; $i < $n; $i++)
{
if ($num[$i] & 1 == 1)
$odd ++ ;
else
$even ++ ;
}
echo "Number of even elements = $even
and Number of odd elements = $odd" ;
?>
Create counters $evens and odds. Then Loop through elements in array check if number is odd
using Ternary Operator (condition) ? true : false;, and $num & 1 return true if number is odd.
$nums = array(5,5,0,1,2,1,1,6,1);
$odds = $evens = 0;
foreach ($nums as $num) {
$num & 1 ? ++$odds : ++$evens;
}
echo "Odds: $odds, Evens: $evens"; //Odds: 6, Evens: 3
Just count only number of odds, Because If we count number of Odds in array, It would be easy to know number of Evens by subtract number of elements in array with number of Odds
$nums = array(5,5,0,1,2,1,1,6,1);
$odds = 0;
foreach ($nums as $num) {
$odds += $num % 2;
}
$evens = count($nums)-$odds;
echo "Odds: $odds, Evens: $evens"; //Odds: 6, Evens: 3

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

Problems pushing an integer into an array

I've been trying to solve Project Euler problem 1 and I feel I'm missing something fundamental. Would you please help me fix my bug?
I tried this first:
<?php
/*
** Project Euler Problem 1
** If we list all the natural numbers below 10 that are multiples of 3 or 5,
** we get 3, 5, 6 and 9. The sum of these multiples is 23.
** Find the sum of all the multiples of 3 or 5 below 1000.
*/
$numberOne = 3;
$numberTwo = 5;
$endingIndex = 1000;
$multiplesOfNumbers = array();
for ($index = 1; $index <= $endingIndex; $index++) {
if ($index % $numberOne == 0 && $index % $numberTwo == 0) {
$multipleOfNumbers[] = $index;
}
}
echo $multiplesOfNumbers;
?>
Output:
Array
So I tried to do it with array_push instead, like this:
<?php
/*
** Project Euler Problem 1
** If we list all the natural numbers below 10 that are multiples of 3 or 5,
** we get 3, 5, 6 and 9. The sum of these multiples is 23.
** Find the sum of all the multiples of 3 or 5 below 1000.
*/
$numberOne = 3;
$numberTwo = 5;
$endingIndex = 1000;
$multiplesOfNumbers = array();
for ($index = 1; $index <= $endingIndex; $index++) {
if ($index % $numberOne == 0 && $index % $numberTwo == 0) {
// $multipleOfNumbers[] = $index;
array_push($multiplesOfNumbers, $index);
}
}
echo $multiplesOfNumbers;
?>
The output is the same. What am I missing?
Try this way:
print_r($multiplesOfNumbers);
echo will not print the array elements. use print_r instead
You have to loop through the array to get the values of the array (using a foreach) or use something like var_dump() or print_r() to echo the array.

How can I find how often the sum of three consecutive values in a set equal a certain value?

9 numbers. Count how often the sum of 3 consecutive numbers in this set of numbers equaled to 16:
2, 7, 7, 1, 8, 2, 7, 8, 7,
The answer is 2. 2 + 7 + 7 = 16 and 7 + 1 + 8 = 16
But I can't seem to get the answer, because I don't know how to "loop" back and skip the first number and do the process over.
How would one be able to solve this utilizing arrays, and how would one solve this without utilizing arrays?
The 9 numbers are randomly generated, and it has to stay that way, but for the sake of solving, I used seed of 3 using srand(3). This is my current code below:
<?php
srand(3);
$count = 1;
$answer = 0;
$num1 = 0;
$num2 = 0;
$num3 = 0;
for ($i = 0; $i < 9; $i++)
{
$num = rand(0, 9);
echo $num . ', ';
if ($count == 1)
$num1 = $num;
else if ($count == 2)
$num2 = $num;
else if ($count == 3)
{
$num3 = $num;
$count = 1;
}
if ($num1 + $num2 + $num3 == 16)
$answer++;
$count++;
}
echo '<br />*******' . $answer . '*******';
?>
Obviously this isn't the right answer because I had to do the check again, but skipping the first number, and so on and so forth until (the last indexed number - index 3)
Probably not the most efficient solution, but its hard to think at 11 at night:
$array = array(2, 7, 7, 1, 8, 2, 7, 8, 7);
$count = count($array);
for ($x = 0; $x < $count; $x++) {
$parts = array_chunk($array, 3);
foreach ($parts as $part) {
if (array_sum($part) == 16 && count($part) == 3) {
print_r($part);
}
}
array_shift($array);
}
Another solution which I think is the more efficient, logic similar to what #Jeroen Vannevel answered:
$array = array(2, 7, 7, 1, 8, 2, 7, 8, 7);
$count = count($array) - 2;
for ($x = 0; $x < $count; $x++) {
if ($array[$x] + $array[$x+1] + $array[$x+2] == 16) {
echo "{$array[$x]} + {$array[$x+1]} + {$array[$x+2]} = 16 <br />";
}
}
Not a PHP writer but this could be your approach:
Fill the array from indices 0 up to and including 8 with a random value.
Iterate from index 0 to index [length - 3]. (length is 9)
Calculate the sum of the values on index [currentIndex], [currentIndex + 1] and [currentIndex + 2].
Whenever the value of that sum equals 16, increment your [count] variable by 1.

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