macford
macford

Reputation: 23

PHP - Trouble adding value to third dimensional array

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?

Upvotes: 2

Views: 102

Answers (2)

dnagirl
dnagirl

Reputation: 20456

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);

Upvotes: 0

deceze
deceze

Reputation: 522135

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);

Upvotes: 6

Related Questions