Reputation: 1783
I have an array with a random number of words. It can contain a single word as a minimum or more than 10 words. Example:
$words = array (
0 => 'This',
1 => 'is',
2 => 'my',
3 => 'word'
)
Now, lets say i want to echo out 6 words from this array, starting over when we reach the end of the array. I want the logic to be something like this
for ($i=0; $i < 6 ; $i++) {
//if $words[$i] exist, print it, else reset the array and start over until we reach all 6
}
I'd like the result to be: "This is my word this is"
I struggle to figure out the maths for this. Any help would be much appreciated!
Thanks
Upvotes: 0
Views: 65
Reputation: 307
for ($i = 0; $i < 6 ; $i++) {
if(!empty($words[$i]))
echo $words[$i];
else
for($j = 0 ; $j <= $i; $j++){
echo $words[$j];
}
}
Upvotes: 0
Reputation: 4872
To handle if $words[$i] exist, print it, else reset the array
I'd use something neater $i % count($array)
, for example.
$array = array(
'0' => 'This',
'1' => 'is',
'2' => 'my',
'3' => 'word'
);
for ($i = 0; $i < 6; $i++) {
echo $array[$i % count($array)] . ' ';
}
// "This is my word This is "
Or if you wanted your exact output as specified in your question, (no spaces on the end), I'd probably do
$string = '';
for ($i = 0; $i < 6; $i++) {
$string .= $array[$i % count($array)] . ' ';
}
echo trim($string);
// "This is my word This is"
or alternatively something like
echo $array[$i % count($array)] . ($i == 5 ? null : ' ');
// "This is my word This is"
Upvotes: 2
Reputation: 1018
Your array is defined wrong to begin with:
$words = array (
0 => 'This',
1 => 'is',
2 => 'my',
3 => 'word'
);
Now to print it you can do:
for ($i=0; $i < 6 ; $i++) {
if(isset($words[$i])) { echo $words[$i] . ' '; }
}
For your more strange requirement:
for ($i=0; $i < 6; $i++) {
echo $words[$i % count($words)], ' ';
}
Upvotes: 1
Reputation: 454
Try this :
for ($i=0; $i < 6 ; $i++) {
echo $words[$i%(sizeof($words))];
}
Upvotes: 0
Reputation: 42460
The most elegant solution that does not require a second variable for iteration would probably be to use the modulo operator:
for ($i=0; $i < NUMBER_OF_WORDS ; $i++) {
echo $words[$i % count($words)] . ' ';
}
This will echo
NUMBER_OF_WORDS
words of your array $words
and start at index 0 again once all words of the array have been used.
Upvotes: 1
Reputation: 876
for($i=0; $i<6; $i++) {
if($i >= sizeOf($words)) {
echo $words[$i % sizeOf($words)];
}
else { echo $words[$i]; }
}
Should do the trick.
Upvotes: 0
Reputation: 1700
Try this:
$words = array('first', 'second', 'third');
$result = '';
$index = 0;
$words_count = count($words);
for ($i = 0; $i < 5; ++$i) {
$result .= ' ' . $words[$index];
++$index;
if ($index >= $words_count) {
$index = 0;
}
}
die(var_dump($result));
Upvotes: 2
Reputation: 3514
Just try something like this:
$n = 0;
for ($i=0; $i < 6 ; $i++) {
echo $words[$n];
$n++;
if($n == count($words){
$n -= count($words);
}
}
If you reach the end of your array it will reset $n to zero;
Upvotes: 0