0

I have an array of float values in PHP and I want to turn the array into a bar chart using CSS. Each float value represents a percentage, so if a value is 50.0 then the bar should be 50% of a certain height. I am new to CSS, so I was wondering if anyone could show me how I would go about doing this.

I believe it should look something like this. I doubt that this code would work, but it's an example.

<?php
    $values = array(50.0, 20.0, 30.0, 45.0); //This is the array of percentage values
?>

<style>
    <?php
    for ($i = 0; $i < count($values); $i++) //Create a new bar for each value
    {?>  
        #bar
        {
            height: <?php 300 * ($values[$i] / 100.0); ?> px; //Specify the height of each bar
            width:  30px;
        }
    <?php
    }?>
</style>

Edit:

I've added the code suggested by Tom, but my web page currently produces no bars. Here is the full code for my PHP file. Why does it not produce any CSS content?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Visualisation result</title>
    <style>
        .bar
        {
            color: #00ff21;
            width:  30px;
        }    
    </style>
</head>
<body>
    <?php            
        $values = array(50.0, 20.0, 30.0, 45.0);

        for ($i = 0; $i < count($values); $i++)
        {
            $currentHeight = 300 * $values[$i] / 100.0; ?>  
            <div class="bar" style="height: <?php echo($currentHeight); ?> "></div>        
        <?php
        }
    ?>
</body>
</html>
1

1 Answer 1

2

Your approach won't work, as you will be writing out several different rules for the same selector. It is invalid in HTML to have multiple values with the same ID "bar" anyway.

I guess you could do something like this:

.bar {
    width: 30px;
}
<?php
for ($i = 0; $i < count($values); $i++) { ?>  
    <div class="bar" style="height:<?= 300 * $values[$i] / 100.0 ?>"></div>        
<?php 
} ?>

This generates the elements using the loop, setting their height using the style attribute. I have used the shorthand <?= instead of <?php echo (you weren't doing either in your question).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.