How to expand an array_shift beyond the number of indexes?

0

I have a question. I put the code just below before starting a while but inside the loop, when calling array_shift($cores) , it applies the classes while loop is <= that the amount of indexes, that is, índice 4 it no longer applies more classes.

If I then put 10 items inside the loop, 6 will get classless some probably because this statement puts index without repeating it.

$cores = ["primary", "secondary", "tertiary", "quaternary"];
shuffle($cores);

LOOP

if ( $empr->have_posts() ) {
    while ( $empr->have_posts() ) { $empr->the_post(); ?>
        <div class="team-item <?php echo array_shift($cores); ?>"> ...

Question: How to continue applying the classes? An example can be viewed here in the in> OTHER DEVELOPMENTS .

    
asked by anonymous 21.12.2015 / 21:30

2 answers

3

Using array_shift

You can rotate the array like this:

array_push( $cores, array_shift($cores) );

Applied to code:

if ( $empr->have_posts() ) {
    while ( $empr->have_posts() ) {
        $empr->the_post();
        echo '<div class="team-item ' . $cores[0] . '">';
        array_push( $cores, array_shift($cores) );
        ...

Explanation:

When you give array_shift to { 1, 2, 3, 4 } , the function will return 1 , and at the same time the array will become { 2, 3, 4 } .

Next, we give array_push , getting the 1 returned, and adding to the end of the same array . Since the array has been shortened to { 2, 3, 4 } , when we add the 1 at the end it will { 2, 3, 4, 1 } , and so on: { 3, 4, 1, 2 } , { 4, 1, 2, 3 } , { 1, 2, 3, 4 } ...


Alternative with module

Here's an alternative that I find even leaner than with array_shift .

$i = 0;
if ( $empr->have_posts() ) {
    while ( $empr->have_posts() ) { $empr->the_post(); ?>
        <div class="team-item <?php echo $cores[$i++ % 4]; ?>"> ...
    
21.12.2015 / 21:47
2

I do not know if I understood correctly, but array_shift removes the first item right?

I imagine something like this will solve your problem:

$cores = ["primary", "secondary", "tertiary", "quaternary"];
shuffle($cores);
$tmp = null;

if ( $empr->have_posts() ) {
while ( $empr->have_posts() ) { $empr->the_post(); ?>
    $tmp = is_null($tmp) ? $cores : $tmp;
    <div class="team-item <?php echo array_shift($tmp); ?>"> ...

I have studied here, and I believe that array_pop is more appropriate because it does not require you to update the array index. It would look like this (I changed the ternario tb to see if it goes):

$cores = ["primary", "secondary", "tertiary", "quaternary"];
shuffle($cores);
$tmp = null;

if ( $empr->have_posts() ) {
while ( $empr->have_posts() ) { $empr->the_post(); ?>
    $tmp = !$tmp ? $cores : $tmp;
    <div class="team-item <?php echo array_pop($tmp); ?>"> ..

The array_pop does the same thing as the shift but in the last element of the array, as you do not mind the order I imagine it will serve the same, but with performace improvement.

    
21.12.2015 / 21:38