Fri, 17 May 2024


Array Each Function - Return Alternative

By: Peter, NetArt Media
Wed, 1 August 2018
Array Each Function - Return Alternative

PHP array 'each' is actually a 'branch', if you will, of the 'foreach' statement. Which is fairly obvious, given the word 'for' has been removed from the term. In the example below there isn't that much less coding that what I may use for a basic foreach statement, but within a more complex context, it could save having to write out several lines of code. PHP is a rather quick development language, for the most part, but the more lines a script has to process, the slower the script or page will take to load.


The above code block uses the array list function, which I introduced last week. I turned the array into a list, then defined a while statement which loops through each $key and it's $value within the workday array. I chose to replace the comma for a dash, which makes each line more reader friendly, in my opinion.

1. Monday - Take inventory of store stock and report to head office.
2. Wednesday - Fill in order sheets and make sure stock is available for following week.
3. Friday - Organize booking events for following week and call guests who have cancelled.

I also replaced the double arrow, which is used quite frequently when returning array data with PHP. By changing the arrow to a period, the result becomes a 'pseudo' ordered list. I use a simple CSS div property when I experiment with these examples on my development server. However, a person could actually skip the '$key' return with this array example and utilize an HTML ordered list to create numbers automatically.


By creating an automatically formatted ordered list, we don't even need to include the '$key' variable in our echo statement. '$key' must be included in the while statement though, so always remember that when using this method of returning array data. As would be expected, using an HTML ordered list configuration returns the exact same result as the one above. The resulting source code is shown below.


I hope this short tool box article is helpful to you in some way. There are many alternatives for returning data with PHP, and the more coders are aware of, the better off they will be whenever they stumble onto an unexpected situation.


Category: Web Development
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox