From the course: PHP Tips, Tricks, and Techniques

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Modifying each element in an array

Modifying each element in an array

From the course: PHP Tips, Tricks, and Techniques

Modifying each element in an array

- [David] Hi, I'm David Powers, and welcome to this week's edition of PHP Tips, Tricks, and Techniques designed to help you become a smarter, more productive PHP developer. This time we'll look at modifying each element in an array using two approaches: a foreach loop, and the built-in array_map() function. We'll see how they differ and discuss why you might choose one in preference to the other. In the exercise files for this video I've defined this function, addTax. It takes two arguments, a $net price and a tax $rate, and it returns the tax inclusive price formatted to two decimal places. Then I've got this indexed array of three $prices, followed by this foreach loop that attempts to modify each element in the array, setting the tax rate to 10%. Then I'm inspecting the result with print_r. Now, if you've been using PHP for any length of time, you'll know that this won't work. Let's just verify that by loading this file into a browser to run the script. And there's the result:…

Contents