Digits with numbers from 1 to 100 and every 10 numbers keep the division of the number by 10
This code does what I want, but I think there is a better charm that this code could do in multiple lines, especially if the loop is from 1 to 1000
for ($i=1; $i <= 100; $i++)
{
if ($i <= 10 ) {
$id = 1;
}
elseif ($i > 10 && $i <= 20) {
$id = 2;
}
elseif ($i > 20 && $i <= 30) {
$id = 3;
}
elseif ($i > 30 && $i <= 40) {
$id = 4;
}
elseif ($i > 40 && $i <= 50) {
$id = 5;
}
elseif ($i > 50 && $i <= 60) {
$id = 6;
}
elseif ($i > 60 && $i <= 70) {
$id = 7;
}
elseif ($i > 70 && $i <= 80) {
$id = 8;
}
elseif ($i > 80 && $i <= 90) {
$id = 9;
}
elseif ($i > 90 ) {
$id = 10;
}
$array = ['id' => $id, 'order' => $i];
Provider::create($array);
}
+3
source to share
2 answers
Use the code below:
<?php
$arr = array();
for ($i=1; $i <= 100; $i++)
{
$id = $i/10;
if ($i%10 == 0) {
echo "id: ".$id." Order: ".$i."\n";
$arr[$id] = $i;
}
}
print_r($arr);
Output
id: 1 Order: 10
id: 2 Order: 20
id: 3 Order: 30
id: 4 Order: 40
id: 5 Order: 50
id: 6 Order: 60
id: 7 Order: 70
id: 8 Order: 80
id: 9 Order: 90
id: 10 Order: 100
Array
(
[1] => 10
[2] => 20
[3] => 30
[4] => 40
[5] => 50
[6] => 60
[7] => 70
[8] => 80
[9] => 90
[10] => 100
)
Demo: Click here
+1
source to share