I'm trying to learn simple arrays but I'm thinking I used an extra step and made it too complicated. 😃
My goal: to regex a string of animal names and prices, and end up with a simple array of animal=>price.
Here's what I did:
$string = 'the "bear" is 4.00 the "goat" is 2.00 and the "cat" is 12.00';
I use preg_match to find the animal and price (the "animal" is always between quotes, and the price is always a normal dollar amount):
preg_match_all("/\"(.*?)\".*?(\d{1,2}\.\d{2})/",$string,$matches);
using "print_r" I see that $matches[1] holds the animals and $matches[2] holds the prices.
Array
(
[0] => Array
(
[0] => "bear" is 4.00
[1] => "goat" is 2.00
[2] => "cat" is 12.00
)
[1] => Array
(
[0] => bear
[1] => goat
[2] => cat
)
[2] => Array
(
[0] => 4.00
[1] => 2.00
[2] => 12.00
)
)
Now I create a new array to load the aforementioned "$matches array" into:
$animal_price = array();
for ($i=0;$i<count($matches);$i++){
$animal_price[$matches[1][$i]]=$matches[2][$i];
}
Now I'm done. When I loop through that final array, I get the simple [bear] => 4.00 and [goat] => 2.00
My question: did I do create that last array and then loop through the first array to fill it? Or is there something more efficient that I can do?
Thank you!!
p.s. sorry, I am just learning. I've spent about a week trying to figure out this on my own, I sure could use your input. 🙂