I have a string which can be
$string = "value.";
OR
$string = "value1, value2.";
I want to iterate through this string getting each item which are -> value
(in first example) and -> value1
AND value2
in the second (without the comma or the dot in the end).
I was thinking of;
Is this the right way of doing it?
I am new to PHP and trying to learn best practices and best ways of solving the issues.
Thank you.
You're absolutely right, you could do it like this:
$string = 'foo, bar, baz.';
$string = preg_replace('/\.$/', '', $string); //Remove dot at end if exists
$array = explode(', ', $string); //split string into array seperated by ', '
foreach($array as $value) //loop over values
{
echo $value . PHP_EOL; //print value
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With