Search code examples
phphtmlarraysloopsecho

How to echo data array


I'm new for this, can anyone solve my problem? this is my code :

<?php

$data = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
$datastart = 3;
$string = join(',', $data);
echo $string;

?>

This echo will be result :

Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday 

I want a result like this:

Wednesday,Thursday,Friday,Saturday,Sunday,Monday,Tuesday

thank you for the answer :)


Solution

  • You can use array_slice to extract the portions of your array in the order you want to output them, and then array_merge to put them back together:

    $data = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
    $datastart = 3;
    $string = implode(',', array_merge(array_slice($data, $datastart), array_slice($data, 0, $datastart)));
    echo $string;
    

    Or you can use a simple for loop:

    $len = count($data);
    $string = '';
    for ($i = 0; $i < $len; $i++) {
        $string .= ($i > 0 ? ',' : '') . $data[($i + $datastart) % $len];
    }
    echo $string;
    

    Output:

    Wednesday,Thursday,Friday,Saturday,Sunday,Monday,Tuesday
    

    Demo on 3v4l.org