Hello All,

I've been dabbling with PHP for a couple years now, nothing serious, but something has really been bugging me. I see -> and => being used all the time, almost as assignment operators but can't find squat about them in any operator list, either on php.net, or in the two books I have. Nothing in the indices. It's really frustrating. What the heck do these two "things" do??

Please help before I go MORE insane!

Thanks,

Steel Rat

-> is used for object oriented PHP. So if you have a class called user and the user class has a function called login and a variable called name. You would create an object from the class called John maybe. So to log John in you would call the login function like so $John->login(); or if you wanted John's name you would call $name = $John->name;

I did this really quick so sorry if it doesn't make sense.

Thanks, DI.

That sorta helps. Does the -> have a name I can search on? It's not an operator, is it a directive?

And any clues about the => ?

Thanks again,

SR

Thanks again.

I guess my problem is they don't explain what => or -> actially is, they just show them in use. => seems to be an assignement operator, but it also seems to be totally useless, since the foreach already does an assignment if you do

foreach ($a as $b)

There's the assignment. Using

foreach ($a as $c => $b)

just seems totally useless to me. What am I missing?

When you use foreach($a as $c => $b) then the key is copied to the variable $c. This gives you an easy way of changing the origional array if you want. Like so:

foreach($a as $c => $b)
{
  $b = '<div>' . $b . '</div>';
  $a[$c] = $b;
}

Ok, so it's not a simple assignment. it's a key or index assignment. I guess that makes sense. I see the => used all the time when populating variables for templates, but just couldn't figure out what it was doing.

Thanks again for your help!

None of that seemed easy to understand

Yes -> is used for objects such as

$apple = new Fruit();
$apple->color = 'red';
$apple->price = 1;

while => is used for arrays

$apple = array();
$apple['price'] = 1;
$apple['color'] = 'red';

$pear = array('price' => 2, 'color' => 'green');

and yes, it gets used in foreach because it's describing the relationship between the array key and the value.

This article has been dead for over six months. Start a new discussion instead.