Jithin Varghese
Jithin Varghese

Reputation: 2228

how to remove space and repeated digit from string

How to remove space and repeated digit from string. My piece of code is,

<?php
if(@$get_colors_l > 0)
{
    while($get_colors_r = mysqli_fetch_array($get_colors))
    {
        echo $get_colors_r["color"];  //result is 1,2 1
        $color = explode(",", $get_colors_r["color"]); 

        foreach($color as $color_code)
        {   
            echo $color_code; // result is 1 2 1
            $get_single_color = $filter -> getSingleColor($color_code);

            while($get_single_color_r = mysqli_fetch_array($get_single_color))
            {
?>
                <p class="inline1"><button style="background-color:<?php echo $get_single_color_r["color_code"]; ?>; height:25px; width:25px; border:none"></button></p>
<?php
            }
        }
    }
}
?>

Now the result of above code is 1 2 1. I want it as 1 2. I want to make repeated digit as single.

How to done this. I have no idea. Thanks in advance.

Upvotes: 1

Views: 31

Answers (2)

Jithin Varghese
Jithin Varghese

Reputation: 2228

After search a lot finaly i have got the answer.

            <?php
            if(@$get_colors_l > 0)
            {
                while($get_colors_r = mysqli_fetch_array($get_colors))
                {
                    $color = explode(",", $get_colors_r["color"]);

                    foreach($color as $color_code)
                    {
                        $color_code = $color_code;
                    }

                    $get_single_color = $filter -> getSingleColor($color_code);

                    while($get_single_color_r = mysqli_fetch_array($get_single_color))
                    {
            ?>
                        <p class="inline1"><button style="background-color:<?php echo $get_single_color_r["color_code"]; ?>; height:25px; width:25px; border:none"></button></p>
            <?php
                    }
                }
            }
            ?>

Upvotes: 1

Andrius
Andrius

Reputation: 5939

To remove duplicated from an array, you'll need to use PHP's array_unique().

It would work as this according to your code:

$color = explode(",", $get_colors_r["color"]); 
$color = array_unique($color);

Full simplified example to show how it's working:

<?php 
$colors_str = "1,2,1";
$colors_arr = explode(",",$colors_str);
var_dump($colors_arr);
$colors_arr = array_unique($colors_arr);
var_dump($colors_arr);

Upvotes: 2

Related Questions