Get items from a list and display them in random order

Discussion in 'PHP' started by Joobz, Nov 12, 2007.

  1. #1
    is there an easy way to have a list of 50 items (one per line) and to include them into a section of a webpage (as php include) listed in a different random order each time?

    I would also like to know if I can limit the output to maybe the first random 20 items.
     
    Joobz, Nov 12, 2007 IP
  2. decepti0n

    decepti0n Peon

    Messages:
    519
    Likes Received:
    16
    Best Answers:
    0
    Trophy Points:
    0
    #2
    $items = explode("\n", $i_dont_know_where_the_items_are);
    $keys = array_rand($items, 20);
    foreach ($keys as $key) {
        echo $items[$key];
    }
    PHP:
    I think
     
    decepti0n, Nov 12, 2007 IP
  3. Joobz

    Joobz Peon

    Messages:
    598
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you but wouldn't there be some statement where I would identify the file containing the list?
    ie: $listfile = "listfile.txt"
     
    Joobz, Nov 13, 2007 IP
  4. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #4
    
    <?php
    /**
     * @author Interviolet
     * @package [$package]
     * @filename [$filename]
     * @copyright 2007
     */
    function random_list_from_file( $filename, $limit = null )
    {
    	if( ( $array = file( $filename ) ) )
    	{
    		$array = array_map( 'format_list', $array );
    		
    		shuffle( $array );
    		
    		return $limit ? current( array_chunk( $array, $limit ) ) : $array ;
    	}
    }
    /**
    * Callback to format each line of list with html tags, edit as appropriate
    **/
    function format_list( $list, $start = "<p>", $end = "</p>" )
    {
    	return sprintf( "%s%s%s", $start, trim( $list ), $end );
    }
    
    echo implode("\n", random_list_from_file( "test.txt", 20 ) );
    ?>
    
    PHP:
    leave out the limit parameter to return the whole array ....
     
    krakjoe, Nov 13, 2007 IP
  5. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #5
    $listfile = file("listfile.txt");
    PHP:
    Edit: I opened this page a while back and just replied. A little late I guess.
     
    MMJ, Nov 13, 2007 IP