Multi For loop php - php

How to use multi for loop with array.
I'm trying to iterate over the contents of an array.
This is the code I have tried.
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
for($i = 0; $i < 5; $i++){
echo $arr[$i];
for($j = 0; $j < $i; $j++){
echo $arr[$j];
}
echo "<br />";
}
echo "<br/>";
for ($i = 0; $i <= count($arr); $i++){
if ($i%3 == 0){
echo $arr[$i-1] . " " . "<br />";
} else {
echo $arr[$i-1] . " ";
}
}
this is the result i got
1
2 1
3 1 2
4 1 2 3
5 1 2 3 4
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
I want to display a result like this and how it works:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
1 | 6 | 11
2 | 7 | 12
3 | 8 | 13
4 | 9 | 14
5 | 10 | 15
Thank you

Two separate questions:
The first one, I'd do like this:
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
$prev =0;
for ($i=1; $i<=5; $i++) {
print implode(" ", array_slice($arr, $prev, $i)) . "<br>\n";
$prev += $i;
}
You could replace the array_slice() with a for loop if that makes you happier. The second one:
$cols = 3;
$rows = floor(count($arr)/$cols);
for ($i = 0; $i < $rows; $i++) {
for ($j=0; $j<=$cols; $j++) {
print $arr[$i+$j*$rows] ?? ' ';
if ($j < ($cols-1)) print " | ";
}
print "<br>\n";
}

Related

Nested Loop For loop with two inner for loop in PHP

I require a nested for loop for my php website which gives me results as follows.
I want to two integers incrementally - one stops at 12 and other continues until the specified values.
If one string is $i and second string is $j than I want output as:
$i 1 2 3 4 5 6 7 8 9 10 11 12
$j 1 2 3 4 5 6 7 8 9 10 11 12
$i 1 2 3 4 5 6 7 8 9 10 11 12
$j 13 14 15 16 17 18 19 20 21 22 23 24
$i 1 2 3 4 5 6 7 8 9 10 11 12
$j 25 26 27 28 29 30 31 32 33 34 35 36
It should be repeated up to n values.
You can try this:
<?php
createMatrix(40);
function createMatrix($jMax)
{
$jVal = 0;
while ($jVal < $jMax) {
// print line $i
echo ('$i' . "\t");
for ($iVal = 1; $iVal <= 12; $iVal++) {
echo "$iVal\t";
}
echo "\n";
// print line $j
echo ('$j' . "\t");
for ($j = 1; $j <= 12; $j++) {
$jVal++;
echo "$jVal\t";
if ($jVal === $jMax) {
echo "\n";
break;
}
}
echo "\n";
}
}
OUTPUT:

How can I print this sequence of numbers using PHP?

I want to try this sequence in PHP: 10 9 8 7 6 5 4 3 2 1 3 4 5 6 7 8 9 10. The condition is I can use only one loop.
I tried this code and I know it will infinite after it prints 0. But I do not find any way to fix it.
<?php
for($i = 10; $i >= 0; $i--){
echo $i;
if($i == 0){
echo $i++;
}
}
Now I can't test it but I think it works:
<?php
$x = 10;
$cond = "DESC";
for($i = 20; $i >= 0; $i--){
echo $x;
If ( $x == 1 ) $cond = "ASC";
$cond == "DESC" ? $x-- : $x++;
}
?>
If you want to have a more simple solution you can use array:
<?php
$arr = Array (10,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,10);
foreach ($arr as $int){
echo $int;
}
?>
You could do this with a one-liner, if you're looking for "simple":
foreach (array_merge(range(10, 1, 1), range(3, 10, 1)) as $i) {
echo "$i ";
}
Result:
10 9 8 7 6 5 4 3 2 1 3 4 5 6 7 8 9 10
This makes the two arrays, [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ] and [ 3, 4, 5, 6, 7, 8, 9, 10 ], concatenates them, and then runs through the resultant array.

Calculating Median of an array in PHP

I'm trying to figure out how to calculate the median of an array of randomly generated numbers. I have the array all set up, but I'm having trouble putting together a function for the calcuation.
This is what I have so far:
//array
$lessFifty = array();
$moreFifty = array();
//number generation
for ($i = 0; $i<=30; $i++) {
$number = rand(0, 100);
//Sorting <50>
if ($number < 50 ) {
$lessFifty[] = $number;
} else {
$moreFifty[] = $number;
}
}
echo print_r($lessFifty);
echo "<br>" ;
echo print_r($moreFifty);
//Average
echo "<p> Average of values less than fifty: </p>";
print array_sum($lessFifty) / count($lessFifty) ;
echo "<p> Average of values greater than fifty: </p>" ;
print array_sum($moreFifty) / count($moreFifty) ;
//Median
$func = function (median ($array, $output = $median)){
if(!is_array($array)){
return FALSE;
}else{
switch($output){
rsort($array);
$middle = round(count($array) 2);
$total = $array[$middle-1];
break;
return $total;
}
}
echo $func ;
I'm pretty sure that I'm doing this median section completely wrong. I'm just learning and its proving to be a challenge.
Be careful about how you write your for() loop. If you want 30 entries, then you should not use <= or you will end up with 31 because $i starts with 0.
Build an array of the random numbers, then sort them.
Then determine if you have a central entry (odd array length) or if you need to average the middle two entries (even array length).
Here is a modern implementation of a median method posted in 2022 on CodeReview.
Code: (Demo)
$limit = 30; // how many random numbers do you want? 30 or 31?
for ($i = 0; $i < $limit; ++$i) {
$numbers[] = rand(0, 100);
}
var_export($numbers);
//echo "\n---\nAverage: " , array_sum($numbers) / $limit;
echo "\n---\n";
sort($numbers);
$count = sizeof($numbers); // cache the count
$index = floor($count/2); // cache the index
if (!$count) {
echo "no values";
} elseif ($count & 1) { // count is odd
echo $numbers[$index];
} else { // count is even
echo ($numbers[$index-1] + $numbers[$index]) / 2;
}
Possible Output:
array (
0 => 27,
1 => 24,
2 => 84,
3 => 43,
4 => 8,
5 => 51,
6 => 60,
7 => 86,
8 => 9,
9 => 48,
10 => 67,
11 => 20,
12 => 44,
13 => 85,
14 => 6,
15 => 63,
16 => 41,
17 => 32,
18 => 64,
19 => 73,
20 => 43,
21 => 24,
22 => 15,
23 => 19,
24 => 9,
25 => 93,
26 => 88,
27 => 77,
28 => 11,
29 => 54,
)
---
43.5
After sorting, elements [14] and [15] hold 43 and 44 respectively. The average of these "middle two" values is how the result is determined. (Hardcoded numbers demo)
If you want a short, inflexible, hardcoded snippet, then you can use 30 and 14 and 15 as your predetermined size and indexes.
for ($i = 0; $i < 30; ++$i) {
$numbers[] = rand(0, 100);
}
sort($numbers);
echo ($numbers[14] + $numbers[15]) / 2;

2D array doesnt show data

I have a module in my projects its about the finding free places in the classroom timetable. I am taking variables without problem from database. I need an array which is returns for all classroom which is how many classroom i have in DB. This classrooms also has variable time period 1 till 12 and each period has duration for example if i have in 4th period 3 duration it should write 1 2 3 x x x 7 8 9 10 11 12 and if i have another course in 9th period 2 duration it should be 1 2 3 x x x 7 8 x x 11 12. I did it in 1D array if i give the class_no in query. but it should do it more than a classroom. it shows just numbers 1..12 in 1 line.
$dayy = $_GET['src_day0'];
$drt = $_GET['src_duration0'];
$tm = $_GET['src_time0'];
$faculty_id = $_SESSION['faculty_id'];
$scale = "select DISTINCT t.class_no,t.time,t.duration from ttable t,class c where
day='$dayy' AND (t.faculty='$faculty_id' OR c.faculty='$faculty_id')";
$result = $conn->query($scale);
$x = 1;
while ($rows = $result->fetch_assoc()) {
$class = $rows['class_no'];
$arr = array(
array($x => "$class"),
array(
1 => " 1 ", 2 => " 2 ", 3 => " 3 ", 4 => " 4 ", 5 => " 5 ", 6 => " 6 ",
7 => " 7 ", 8 => " 8 ", 9 => " 9 ", 10 => " 10 ", 11 => " 11 ", 12 => " 12 ",
));
$x++;
}
while ($rows = $result->fetch_assoc()) {
$time = $rows['time'];
$duration = $rows['duration'];
$result1 = ($time + $duration);
for($j=1;$j<$x;$j++)
for ($i = $time; $i < $result1; $i++)
$arr[$j][$i] = "x1";
}
}
for ($i = 1; $i < $x; $i++) {
for ($j = 1; $j < 13; $j++)
echo $arr[$i][$j];
echo "</br>";
In fact you missbuilded your array :)
If your looking your code:
$class = $rows['class_no'];
$arr = array(
array($x => "$class"),
array(
1 => " 1 ", 2 => " 2 ", 3 => " 3 ", 4 => " 4 ", 5 => " 5 ", 6 => " 6 ",
7 => " 7 ", 8 => " 8 ", 9 => " 9 ", 10 => " 10 ", 11 => " 11 ", 12 => " 12 ",
));
$x++;
For each iteration of the loop, you overwrite the array with a new value.
In fact, you need to create a new data and append it on the array.
A way to do it, is the following process:
$arr = [];
while ($rows = $result->fetch_assoc()) {
$arr[ $rows['class_no'] ] = [1 => ' 1 ', 2 => ' 2 ', /*...*/];
}
// free memory if needed
while ($rows = $result->fetch_assoc()) {
for( $i = $rows['time'] ; $i < $rows['time'] + $rows['duration'] ; $i++ ) {
$arr[ $rows['class_no'] ][ $i ] = 'x';
}
}
Here, you create an empty variable $arr of array type. Then, for each data on the loop, you created a new line (for each class_no) with the default values.
On the second loop, you iterate again on the results, but here, you take each array data by class_no and change the correct time value to x

How to right align numbers from an array in php?

I have a problem with aligning numbers from a multidimensional array. I want to print the following result:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
And I want all of the numbers to be aligned with the second digit of the next rows. However my result is that:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
I did this in C# by using:
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write("{0,4}", matrix[row, col]);
}
But how can I receive this result in PHP?
You can use str_pad
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
$test = '';
foreach ($arr as $key => $value) {
if ($key % 4 == 0) {
$test .= "\n";
}
$test .= str_pad($value, 4, ' ', STR_PAD_LEFT);
}
echo "<pre>$test</pre>";
The result would be:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Categories