/    Sign up×
Community /Pin to ProfileBookmark

understandning foreach .

Hey guys , can you tell me what the below construct is really doing ??

[CODE]$categories = array();

foreach (Category::all() as $category) {
$categories[$category->id] = $category->name;
}[/CODE]

what is the foreach loop really creating ?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@ginerjmMar 25.2015 — I believe it is populating the $categories array that you defined with elements from the "Category::all" object(?) where the index is the id property and the value is name property
Copy linkTweet thisAlerts:
@rootMar 25.2015 — No idea about this Laravel business, a bit convoluted and reinventing the wheel if you ask me but...
[CODE]$categories = array();

foreach (Category::all() as $category) {
$categories[$category->id] = $category->name;
}[/CODE]


foreach will take an element in the array variable it is passed, therefore it is reasonable to deduce that ::all() pulls an array from Category and that element that gets pulled is stored in the variable $category

Each time an element is pulled, the property ->name is passed to $categories array and stored under a reference that is set by $category->id

The result is pointless and I will tell you why, you are taking data from a source that is:

a) already an array

b) contains all the data you need and is accessible to populate another array without having to use a foreach approach.

have you tried doing a dump of Category::all() ?
Copy linkTweet thisAlerts:
@NogDogMar 25.2015 — One reason it might not be pointless (and then again, it might) is if that array that is being created will be the output (or part of it), such as for a JSON response for an API call. (And Laravel makes JSON output dirt simple: if the controller just returns an array, it's automatically converted to JSON and output with that Content-Type. ? )

In any case, all() is probably returning a Laravel Collection object, which implements Iterable and other goodies, so that it can be treated in many ways like an array, such as that you can loop through its properties (probably from DB rows) via foreach, even though it's not technically an array, itself.
×

Success!

Help @gautamz07 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...