Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Displaying PHP array in a custom format

Lets say I have an array like this:

$Array = array(1, 5, 7, 11, 16, 20);

I would like to get this result:

1 - - - 5 - 7 - - - 11 - - - - 16 - - - 20

Basically I’d like to get a "-" for non-existent values in the array.
How can I achieve this outcome?
Thanks for your help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can loop through all the numbers you’re interested in and check whether they are in your array:

<pre>
    <?php
        $array = [1, 5, 7, 11, 16, 20];

        for($i = 1; $i <= end($array); $i++) {
            if(in_array($i, $array))
                print $i . ($i==end($array) ? "" : " ");
            else
                echo "- ";
        };
    ?>
</pre>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading