0

I have this code:

$people=array();
$i=0;
foreach ($xml->xpath('//person') as $character) {
if ($character->status!="Active"){

  $people[$i]['fullname']=(string)$character->fullname;
  $people[$i]['status']=(string)$character->status;
  $i++;

    }
}

It creates an array with numeric keys, based on the value of $i. However, I don't actually want that, I want the "fullname" string to be the key but I can't work out how to dynamically assign the key. I was trying things like:

$people[(string)$character->fullname]=>(string)$character->status;

but this just throws errors. I can't work out how to create keys based on variables. Can anyone help, please?

6
  • 1
    What errors does it throw? It certainly looks like it should work. You don't even need the (string) casts. Commented Mar 10, 2011 at 15:13
  • Does it have to be converted to a string? Commented Mar 10, 2011 at 15:15
  • Doh. As the answers below say, you need to change => to =. Commented Mar 10, 2011 at 15:17
  • Thank you everyone, I now have it working, thanks for your help. Commented Mar 10, 2011 at 15:35
  • I see you're a new user here. Welcome! You also may want to take a look at the faq as soon as you find the time. Commented Mar 10, 2011 at 15:43

3 Answers 3

7

Try this again, but with =, not =>:

$people[ (string) $character->fullname ] = (string) $character->status;
Sign up to request clarification or add additional context in comments.

Comments

1

You only use => in the Array definition. Otherwise just use bog-standard assignment:

$people[$character->fullname] = $character->status;

You don't need the casts, as you already have strings. Even if you didn't, you could simply rely on the dynamic typing to convert them as needed on output.

5 Comments

@Tomalak "Why are they not strings in the first place?" Because he's working with XML. They are nodes, but sometimes you need the node value, so you cast to string.
@Alin: You shouldn't ever have to use explicit casts in a dynamically typed language. The type can be inferred when he gets to use the array elements.
Alin - yes, I was having some weird issues when I tried to sort before specifically turning them to strings.
@Max: Ah, you didn't say anything about sorting! Add the casts back in then.
@Tomalak You can run in all sort of issues if you keep the full objects. You may run out of memory. Sorting may not work as expected. And one I encountered a lot of times is saving the information in the session, XML objects don't serialize. As for casting the objects used as the array index, that is redundant, but in coding a certain amount of redundancy increases readability.
0
$people[$character->fullname] = (string)$character->status;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.