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?
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);
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);
Related
Weird scenario I have to admit but it is actually relevant for me, so here goes.
This is a curiosity question since I have a better way to do this already.
I am creating a remote file for other developers to read (file_get_contents) and update. I know I can do this with JSON or creative use of explode() or str_split(), but was wondering if the following was possible.
If you have a text string formatted such that it "looks like" an array (but in PHP's eyes is not actually cast as an array):
//the following string represents the entire contents of the text file myfile.txt
array('key_1' => 'string_1', 'key_2' => 'string_2' ..... 'key_n' => 'string_n');
The string values (eg 'string_1') can literally contain any character...no exceptions. Is there any way that the text file can be read with e.g. file_get_contents():
//this is the remotescript.php file
$arrayString = file_get_contents('path/to/myfile.txt');
and then you, the script writer, literally cast this as an array? (where the type and key => value pairs are set) That is:
$x = someFunction($arrayString);
// this returns ----> $x = array('key_1' => 'string_1', 'key_2' => 'string_2' ..... 'key_n' => 'string_n');
print_r($x); // outputs ----> Array([key_1] => string_1 [key_2] => string_2 ..... [key_n] => value_n)
In a bad attempt I tried casting the string using (array):
$string = file_get_contents('path/to/myfile.txt');
$x = (array)$string;
but this only creates one key where the value is the literal string from the text file.
try
$x = print_r($string, true);
This is my code, it's for have an array :
$zi = '1';
for ($zi = 1; $zi <= $v['Store']['stock']; $zi++) {
$options_array[$zi]= $zi;
}
var_dump($options_array);
Array
(
[0] => 0
[1] => 1
[2] => 2
)
why i have the zero in my result ?
i put $zi at 1, so why ?
As my comment turned out to be correct: The issue is that you already have a property 0 in the $options_array before you even get to the presented code block. You can start with a fresh array using $options_array = [] or $options_array = array() (for older php versions). You can also just remove property 0 with unset($options_array[0]).
In php there are two kinds of arrays, numerically indexed arrays, and associative arrays. Your output seems a little suspect but I can tell you that if all the keys of a PHP array are numeric then the array will be zero based.
I see how you have $zi = '1' above, which is along the lines of what you would have to do to create a one based array, but it would be associative, and you won't be able to simply use the ++ operator. I believe even if you use a string that is a number PHP will still convert to a numerically indexed array. I recommend against trying to implement a one based array, it's insanity.
Hope this page helps http://us2.php.net/manual/en/language.types.array.php
You start setting $options_array at index 1, so index 0 is whatever the default value of the underlying type is. In this case, it's an integer, so the default is 0.
I'm just wondering about how variable variables that point to Arrays handle. Take the code below:
$a = new stdClass();
$a->b = array('start' => 2);
$c = 'b';
$d = 'start';
print $a->$c; // => Array
print $a->$c['start']; // => Array
print $a->$c[0]; // => Array
print $a->$c[0][0]; //=> PHP Fatal error: Cannot use string offset as an array in php shell code on line 1
The first print I expect, the second one I don't, or the 3rd. The 4th is expected after realizing that the evaluation of $a->$c is apparently a string. But then why does this work:
$t = $a->$c;
print $t['start']; //=> 2
I'm asking more because I'm curious than I need to know how to nicely do
$e = 'start';
$a->$c[$e]
Anyone know why I can't index directly into the array returned by the variable variable usage?
It comes down to order of operations and how PHP type juggles. Hint: var_dump is your friend, echo always casts to a string so it is the worst operation for analyzing variable values, esp in debug settings.
Consider the following:
var_dump($a->$c); // array (size=1) / 'start' => int 2
var_dump($a->$c['start']); // array (size=1) / 'start' => int 2
var_dump($a->b['start']); // int 2
var_dump($c['start']); // string 'b' (length=1)
The key here is how PHP interprets the part of $c['start'] (include $c[0] here as well). $c is the string 'b', and when attempting to get the 'start' index of string 'b' this simply returns the first character in the string, which happens to simply be the only letter (b) in the string. You can test this out by using $c = 'bcdefg'; - it'll yield the same result (in this specific case). Also, $c['bogus'] will yield the exact same thing as $c['start']; food for thought, and make sure you do the required reading I linked to.
So with this in mind (knowing that $c['start'] reluctantly returns 'b'), the expression $a->$c['start'] is interpreted at $a->b. That is, the order is $a->($c['start']) and not ($a->$c)['start'].
Unfortunately you can't use () nor {} to steer the parser (PHP SCREAMs), so you won't be able to accomplish what you want in a single line. The following will work:
$e = 'start';
$interim = $a->$c;
echo $interim[$e];
Alternatively, you can cast your arrays as objects (if you have the luxury):
$a->$c = (object) $a->$c; // mutate
var_dump($a->$c->$e);
$interim = (object) $a->$c; // clone
var_dump($interim->$e);
...by the way, referring back up to $c['start'] and $c[0], in regards to $c[0][0] you simply can't do this because $c[0] is the character b in string 'b'; when access the character/byte b it will not have a property of [0].
$a->$c[0]; is actually equal to: array('start' => 0)
so when you did:
print $a->$c[0][0];
You are trying to load an array element from $a->$c[0] at index 0 which does not exists.
however, this will work:
print $a->$c[0]['start'];
An array which is populated it's value from database. when I print_r the array . It shows like below...
Array
(
[term] => These are following selection a) new b) old
)
Here the array is ending with character ) inside the term element " ..selection a) new ..", while it's only a character in the array. So How I would avoid the ending of array with charcters present inside the array ?
What you're viewing is the output of an array with print_r.
Defining an array in PHP is a little different:
$variable = array('inside First a) new, b) old');
print_r($variable);
var_dump($variable); // similar to print_r
There is also another way of doing that:
$variable = array();
$variable[0] = 'inside First a) new, b) old';
So you need to quote your value to get a string.
The array value in your declaration should be a string:
$myArray = array(
0 => 'inside First a) new , b) old';
);
In PHP you need to quote string values:
$array = array(
0 => 'inside First a) new , b) old'
);
See the manual. To be honest this is pretty basic stuff. If you don't know this, I'd suggest going away and getting a basic introduction to PHP book and reading through it...
Having a brain freeze over a fairly trivial problem. If I start with an array like this:
$my_array = array(
'monkey' => array(...),
'giraffe' => array(...),
'lion' => array(...)
);
...and new elements might get added with different keys but always an array value. Now I can be sure the first element is always going to have the key 'monkey' but I can't be sure of any of the other keys.
When I've finished filling the array I want to move the known element 'monkey' to the end of the array without disturbing the order of the other elements. What is the most efficient way to do this?
Every way I can think of seems a bit clunky and I feel like I'm missing something obvious.
The only way I can think to do this is to remove it then add it:
$v = $my_array['monkey'];
unset($my_array['monkey']);
$my_array['monkey'] = $v;
array_shift is probably less efficient than unsetting the index, but it works:
$my_array = array('monkey' => 1, 'giraffe' => 2, 'lion' => 3);
$my_array['monkey'] = array_shift($my_array);
print_r($my_array);
Another alternative is with a callback and uksort:
uksort($my_array, create_function('$x,$y','return ($y === "monkey") ? -1 : 1;'));
You will want to use a proper lambda if you are using PHP5.3+ or just define the function as a global function regularly.
I really like #Gordon's answer for its elegance as a one liner, but it only works if the targeted key exists in the first element of the array. Here's another one-liner that will work for a key in any position:
$arr = ['monkey' => 1, 'giraffe' => 2, 'lion' => 3];
$arr += array_splice($arr, array_search('giraffe', array_keys($arr)), 1);
Demo
Beware, this fails with numeric keys because of the way that the array union operator (+=) works with numeric keys (Demo).
Also, this snippet assumes that the targeted key is guaranteed to exist in the array. If the targeted key does not exist, then the result will incorrectly move the first element to the end because array_search() will return false which will be coalesced to 0 by array_splice() (Demo).
You can implement some basic calculus and get a universal function for moving array element from one position to the other.
For PHP it looks like this:
function magicFunction ($targetArray, $indexFrom, $indexTo) {
$targetElement = $targetArray[$indexFrom];
$magicIncrement = ($indexTo - $indexFrom) / abs ($indexTo - $indexFrom);
for ($Element = $indexFrom; $Element != $indexTo; $Element += $magicIncrement){
$targetArray[$Element] = $targetArray[$Element + $magicIncrement];
}
$targetArray[$indexTo] = $targetElement;
}
Check out "moving array elements" at "gloommatter" for detailed explanation.
http://www.gloommatter.com/DDesign/programming/moving-any-array-elements-universal-function.html