2

I have a this array scenario at first:

$_SESSION['player_1_pawn'][] = 'Warrior';

now when I want to add a third dimensional value like this:

$_SESSION['player_1_pawn'][0]['x'] = 1;

I get this output from

>$_SESSION['player_1_pawn'][0] : '1arrior'

My question is that, how to make that value stays intact as Warrior instead of 1arrior?

2 Answers 2

6

If the value is already a string, ['x'] accesses the first character of that string (yeah, don't ask ;)).

If you want to replace the whole thing with an array, do:

$_SESSION['player_1_pawn'][0] = array('x' => 1);

You cannot have $_SESSION['player_1_pawn'][0] be both the string "Warrior" and an array at the same time, so figure out which you want it to be. Probably:

$_SESSION['player_1_pawn'][0] = array('type' => 'Warrior', 'x' => 1);
Sign up to request clarification or add additional context in comments.

1 Comment

Damn you are faaaaaaaaast :), however the [0] doesn't access the first character in his case, it was the 'x'
0

Your problem is that $_SESSION['player_1_pawn'][0] is a scalar value equal to "Warrior". When you treat a scalar as an array, like you do with $_SESSION['player_1_pawn'][0]['x'] which evalueates $_SESSION['player_1_pawn'][0][0] or "W", you just change the first character in the string.

If you want to keep "Warrior" try this:

$_SESSION['player_1_pawn']=array('Warrior', 'x'=>1);

ETA:

given your requirements, the structure is this:

$_SESSION['player_1_pawn'] = array(
  0 => array('Warrior', 'x'=>1),
  1 => array('Wizard', 'x'=>7), //...
);

Which means you add like this:

$_SESSION['player_1_pawn'][]=array('Warrior', 'x'=>1);

1 Comment

Thank you for your answer, but it needs to be at least two dimension since player 1 has got not only 1 pawn but 5 :D

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.