A
A
Arris2014-09-08 14:30:45
PHP
Arris, 2014-09-08 14:30:45

How to gracefully and quickly display a number in a "bar" (ASCII bar graph)?

A certain function generates a set of numbers from 1..6. It is
necessary to visualize the output as a set of horizontal "stripes" written with symbols , something like this

XXX___
XX____
XXXXX_
XXX___

etc. It is desirable to print exactly "_", and not a space, although this is a complication.
The most obvious solution is to draw such a strip in some loop like this:
for ( $i = 1; $i<= N; $i++) { for ($j=1; $j<= set[$i]; $j++) { echo 'X'; } echo '<br/> '; }

But maybe there is some more elegant solution that I don't see?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arris, 2014-09-08
@Arris

Basically I found the solution :)

$str = str_repeat('_', MAX_STRING_LENGTH);  // в данном случае 6
...
$bar = substr_replace($str, str_repeat('X', $i), 0, $i );
...

But maybe there is something more elegant?

E
Evgeny Petrov, 2014-09-08
@Petroveg

How to increment a string by n number of js ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question