Felix
Felix

Reputation: 1583

Implode string and insert into array?

I can't get the implode function to work with my array. I'm building a site and every time you reload the page the background image is randomly chosen.

I have a loop with different image url:s like this:

<?php 
if( have_rows('pictures', 'option') ):
    while ( have_rows('pictures', 'option') ) : the_row();
        $pictures[] = get_sub_field('picture'); 
        $picturesimploded = "'" . implode("', '", $pictures) . "'";
    endwhile;
endif; 
?>

Below is the code to randomize which url is chosen:

<?php   
    $bg = array( $picturesimploded ); // array of filenames
    $i = rand(0, count($bg)-1); // generate random number size of the array
    $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>

The url is then applied to a div:

<div style="background-image: url( <?php echo $selectedBg; ?> );">

The output however prints all links:

<div style="background-image: url( 'http://example.com/image1', 'http://example.com/image1', 'http://example.com/image1' );">



It seems like the array can't separate the arrays. When I insert the links manually, directly, in the array like this it works:

<?php   
    $bg = array( 'http://example.com/image1', 'http://example.com/image1', 'http://example.com/image1' ); // array of filenames
    $i = rand(0, count($bg)-1); // generate random number size of the array
    $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>

Any ideas how to get the randomizing to work?

Upvotes: 0

Views: 159

Answers (2)

Jens A. Koch
Jens A. Koch

Reputation: 41766

  • flip the array to work on values.
  • use array_rand with 1 to get 1 random element
  • Example: http://ideone.com/cpV2Va

    <?php
    
    $pictures = array();
    if( have_rows('pictures', 'option') ):
        while ( have_rows('pictures', 'option') ) : the_row();
           $pictures[] = get_sub_field('picture'); 
        endwhile
    endif; 
    
    $selectedBg = array_rand(array_flip($pictures), 1);
    

Upvotes: 1

Jonathan
Jonathan

Reputation: 1564

replace

$bg = array( $picturesimploded );

with

$bg = explode( $picturesimploded );

-- when you call

$bg = array( $picturesimploded );

you are making an array with one entry like this:

[0] => 'image,image,image,image,image'

when you use explode it will be like this

[0] => image,
[1] => image,

etc

an alternative would be to do this:

<?php 
$pictures = array();
if( have_rows('pictures', 'option') ):
    while ( have_rows('pictures', 'option') ) : the_row();
        $pictures[] = get_sub_field('picture'); 
    endwhile
endif; 

$i = rand(0, count($pictures)-1); // generate random number size of the array
$selectedBg = $pictures[$i]; // set variable equal to which random filename was chosen


?>

Upvotes: 1

Related Questions