Justin Breen
Justin Breen

Reputation: 135

Loop through array to assign value for every nth item

I have an array containing a range of numbers 1-100:

$range = range(1, 100);

I want to loop through and assign each a value of 1-24. So 1=1, 2=2, 24=24, but then also 25=1, 26=2, 27=3, etc...

How can I loop through $range and apply said values to each number?

Note: I would preferably like to use a forloop, but will take any valid answer.

Upvotes: 1

Views: 182

Answers (4)

For getting your required solution, you can also use the below code -

$range = range(1, 100);
for($i=0; $i<100; $i++){
  if($i < 24){
   echo $range[$i].' = '.($i+1);echo "<br>";
  }else if($i < 48){
   echo $range[$i].' = '.($i-23);echo "<br>"; 
  }else if($i < 72){
    echo $range[$i].' = '.($i-47);echo "<br>";  
  }else if($i < 96){
    echo $range[$i].' = '.($i-71);echo "<br>";
  }else{
    echo $range[$i].' = '.($i-95);echo "<br>";   
  }
}

Upvotes: 1

kscherrer
kscherrer

Reputation: 5766

The modulo operator (%) is the answer

$range = range(1, 100);
$rangeValues = array();

for ($i = 0; $i < count($range); $i++){
    // using modulo 25 returns values from 0-24, but you want 1-25 so I use ($i % 24) +1 instead which gives 1-24
    $rangeValues[$range[$i]] = ($i % 24) +1; 
}

Upvotes: 2

Ravindra Singh
Ravindra Singh

Reputation: 56

$range = range(1, 100);
$offset = 1;
$limit = 24;

for($i = 0; $i < count($range); $i++)
{
    $range[$i] = $offset+($i%$limit);
}
var_dump($range);

Upvotes: 1

JoshulSharma
JoshulSharma

Reputation: 173

Try : php modulo operator (%).

//example loop
$range = range(1, 100);
$yourIndex = array();

for ($i = 0; $i < count($range); $i++){
   //$yourIndex will reset to 1 after each 25 counts in $range
   $yourIndex[$range[$i]] = ($i + 1) % 25;
}

Upvotes: 1

Related Questions