Foreach loop isn’t working for expanding user entered text

I have a textarea in which users write like this:

  • 3x Blue Flower
  • 2* Red Flower
  • 5 Purple Flower
  • Yellow Flower

The point is to echo Blue Flower 3 times etc., while flowers that don’t have numbers are echoed 1 time.

This is my code:

$str = $_POST['tekst'];
$input = explode("n", $str);
foreach($input as $line)
{
    preg_match("/d+/", $line, $matches);
    $line = preg_replace("/d+/",'' ,$line);
    $number = (isset($matches[0]))?$matches[0]:1;
    if(strlen($line)>0){
        foreach ($line as $k=>$val)
        {
            $temp_second_field = $number[$k];
            for ($i = 0 ; $i < $temp_second_field ; $i++ )
            {
                echo $val;
            }
        }
    }
}

Answer

It is because $line is not an array, it is a string. Try replacing this :

// foreach ($line as $k=>$val)
// {
    // $temp_second_field = $number[$k];
    // for ($i = 0 ; $i < $temp_second_field ; $i++ )
    // {
        // echo $val;
    // }
// }
//$temp_second_field = $number[$k];

with this:

for ($i = 0 ; $i < $number ; $i++ )
{
    echo $line;
}

Leave a Reply

Your email address will not be published. Required fields are marked *