I have array in following format. I want to convert it into another format like below.
Array
(
[b2] => 2
[b3] => 8
[b4] => 2
[b5] => 4
)
Is it possible key is converted into PHP variables and its value automatically assigned to variables?Is it possible?
$b = 2;
$b3 = 8;
$b4 = 2
$b5 = 4
thanks
looks like you want extract()
You're looking for the extract() function. You pass in the array you want to extract into the current scope, and that's it. Mind though that you should be very careful when you use this function; for safety, pass EXTR_SKIP in as the second argument to prevent overwriting existing variables, after all you wouldn't want the likes of $_SESSION or $_SERVER throttled by an array with malicious data...
Related
This question already has answers here:
Split Array Into 3 Equal Columns With PHP
(3 answers)
Closed 1 year ago.
I am using list and array_chunk to split arrays. In my first example I split the array into four pieces using list.
I would like to change the number from 4 to say 8 and have it dynamically do this. Instead of manually creating it in the code. Is this possible ? I assume I could use variable naming as listed in my non working second example below.
How it works now :
list($inv0, $inv1, $inv2, $inv3) = array_chunk($val['inventory'], ceil(count($val['inventory']) / 4));
What I would like is to set something $i = 8 and have it automatically split into 8 chunks dynamically .
Something like :
$i = 8
list(${inv.0}, ${inv.1}, ${inv.2}, ${inv.3},${inv.4},${inv.5},${inv.6},${inv.7}) = array_chunk($val['inventory'], ceil(count($val['inventory']) / $i));
So based on my needs I can split the array into X pieces instead of hard coding it to 4 or 8 etc...
You can do a foreach to create the variables you want:
$array = ['a','b','c','d','e','f','g','h'];
$chunk = array_chunk($array,2);
foreach($chunk as $i => $data) {
${'inv'.$i} = $data;
}
print_r($inv0);
print_r($inv1);
die();
Output
Array ( [0] => a [1] => b )
Array ( [0] => c [1] => d )
There are ways, but I don't think it'd be a maintainable approach since you don't even know how many variables you'd need to process.
However, Felipe Duarte provides a working answer and there are some more over here : php how to generate dynamic list()?
But I'd agree with the top answer.
array_chunk already provides you with pretty much what you are looking for:
$chunks = array_chunk($val['inventory'], ceil(count($val['inventory']) / $i));
print_r($chunks);
// [[0] => ['', ''], [1] => ['','']...]
You can then access it via the indices (such as $chunks[0], $chunks[1]).
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 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);
Why am I getting different outputs through print_r in the following two cases!!? This is a bug in php? Is php unable to execute complex hierarchical functions called inside functions?
CASE 1 :
$aa='2,3,4,5,5,5,';
$aa=array_unique(explode(',',$aa));
array_pop($aa);
print_r($aa);
CASE 2 :
$aa='2,3,4,5,5,5,';
array_pop(array_unique(explode(',',$aa)));
print_r($aa)
In the first case, the output is an exploded array :
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 )
In the second case, the output is string :
2,3,4,5,5,5,
This is because array_pop alters its input, and you're passing it a temporary variable (not $aa).
Note the signature in the documentation: array_pop ( array &$array ) - the & means it takes a parameter by reference, and it alters that input variable.
Compare with the other two functions:
array explode ( string $delimiter , string $string , int $limit )
and
array array_unique ( array $array , int $sort_flags = SORT_STRING )
In the first case you update $aa with the output of array_unique(), and then pass that to array_pop to be altered.
In the second case the output of array_unique() will be the same, but this temporary value isn't assigned to a variable & therefore it's forgotten after array_pop is called.
It's worth noting that in that in PHP (unlike say, C++), passing by reference is actually slower than passing by value and therefore is only ever used to modify the input parameter of a function.
In the first case you alter variable as in line 2 bs assigning a new value with the assignment operator =
Before I write my own function to do it, is there any built-in function, or simple one-liner to convert:
Array
(
[0] => pg_response_type=D
[1] => pg_response_code=U51
[2] => pg_response_description=MERCHANT STATUS
[3] => pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6
)
Into:
Array
(
[pg_response_type] => D
[pg_response_code] =>U51
[pg_response_description] =>MERCHANT STATUS
[pg_trace_number] =>477DD76B-B608-4318-882A-67C051A636A6
)
Just trying to avoid reinventing the wheel. I can always loop through it and use explode.
I can always loop through it and use explode.
that's what you should do.
Edit - didn't read the question right at all, whoops..
A foreach through the array is the quickest way to do this, e.g.
foreach($arr as $key=>$val)
{
$new_vals = explode("=", $val);
$new_arr[$new_vals[0]] = $new_vals[1];
}
This should be around five lines of code. Been a while since I've done PHP but here's some pseudocode
foreach element in the array
explode result on the equals sign, set limit = 2
assign that key/value pair into a new array.
Of course, this breaks on keys that have more than one equals sign, so it's up to you whether you want to allow keys to have equals signs in them.
You could do it like this:
$foo = array(
'pg_response_type=D',
'pg_response_code=U51',
'pg_response_description=MERCHANT STATUS',
'pg_trace_number=477DD76B-B608-4318-882A-67C051A636A6',
);
parse_str(implode('&', $foo), $foo);
var_dump($foo);
Just be sure to encapsulate this code in a function whose name conveys the intent.