Derk Jan Speelman
Derk Jan Speelman

Reputation: 11949

Why is php handling for different than foreach?

I made an array $brands inside class Cars, the print_r output looks like this:

Array ( [0] => Array (  [id] => 1 
                        [name] => 'Porsche'
                    ) 
        [1] => Array (  [id] => 2 
                        [name] => 'Bugatti'
                    ) 
        [2] => Array (  [id] => 3 
                        [name] => 'BMW'
                    ) 
    )

But when I'd like to link to a certain brand, I don't want to use strtolower() to make a lowercased hyperlink. I would like to echo $cars->brands[$i]['url'] (instead of strtolower($cars->brands[$i]['name'])).


class Cars {

So I needed to create a for loop, to create the ['url'] key in the array. I thought that a foreach would work:

foreach ($this->brands as $brand => $row) {
    $row['url'] = strtolower($row['name']);
}

But it didn't. Even this did not work: $row['name'] = strtolower($row['name']);.


But this worked, though:

for ($i = 0; $i < count($this->brands); $i++) { 
    $this->brands[$i]['url'] = strtolower($this->brands[$i]['name']);
}

}


My question here is: how? why?

Upvotes: 0

Views: 74

Answers (3)

Touheed Khan
Touheed Khan

Reputation: 2151

because you are overwriting array key('url').

$row is a local copy of $this->brands any changes to $row will not reflect on $this->brands.

change this

foreach ($this->brands as $brand => $row) {
    $row['url'] = strtolower($row['name']);
}

with this

foreach ($this->brands as $brand => $row) {
    $this->brands[$brand]['url'] = strtolower($row['name']);
}

Happy Coding.

Upvotes: 2

user2659982
user2659982

Reputation: 131

You need to work on a reference. Insert a & and it will work

foreach ($this->brands as $brand => &$row) {
    $row['url'] = strtolower($row['name']);
}

or you could work on the original array like:

foreach ($this->brands as $brand => $row) {
    $this->brands[$brand]['url'] = strtolower($row['name']);
}

Upvotes: 4

john Smith
john Smith

Reputation: 17906

if you want to edit the element being iterated you can add a & before $row

foreach ($this->brands as $brand => &$row) {
    $row['url'] = strtolower($row['name']);
}

but this is not necessary, just access the array from the variable available outside of the foreach loop e.g $this->brands

foreach ($this->brands as $brand => $row) {
    $this->brands[$brand]['url'] = strtolower($row['name']);
}

Upvotes: 3

Related Questions