I have the following as a result of a preg_match_all
Array ( [0] => Array ( [0] => $9.70 [1] => $10 [2] => $11.95 [3] => $0.49 [4] => $2.95 [5] => $2.95 [6] => $2.95 [7] => $2.95 [8] => $0.49 [9] => $9.70 ) )
I’m trying to print them all in a foreach loop but getting only first character.
Here’s what I’m trying:
$i = '0';
foreach ($matches[0] as $val) {
echo $val[$i].'<br />';
$i++;
}
Where am I going wrong?
In PHP
foreachworks a different way than you think. Let me explain this using the following code:This code gives the following output:
This happens because the foreach body is called once for every array item, and $value is set to the value of that array item. Using your code one only sees the first character, because PHP allows you to get a single character from a string using array syntax. Long story short, change your code to the following: