Initializing array and getting reference in one line - php

I want to initialize array(in my case it's multidimensional) and I want to retrieve reference to a separate variable so i could access it via that variable.
For example to achieve this im writing two lines
$multidimensional[$some_key] = array();
$item = &$multidimensional[$some_key];
This thing works just fine, but if I wanted to do this in one like I had tried:
$item = &$multidimensional[$some_key] = array(); // syntax error
Question is there a way to do this in single line?

How about:
$item = &($multidimensional[$some_key] = array());
?

Related

Php, new keys and values added inside loop dissapear outside loop

For a school assignment I'm trying to split stockitems with product details like colour and size in the title into groups of stockitems with different variants. I've got as far as having them all split, but I just can't figure out how to add this information to the $stockItem array. ($stockItem is inside the array $stockItemGroup which is inside the array $stockItemGroups).
When I try to add information to the array inside the loop, I cannot access that information outside the loop. If I use print_r on the entire array after this loop has completed the new information is not displayed.
for($i = 0; $i < count($stockItemGroup); $i++){
$stockItem = $stockItemGroup[$i];
$restString = str_replace($similarString, "", $stockItem['StockItemName']);
$colour = getColour($restString, $allColours);
$restVariant = getRestVariant($restString, $allColours);
$stockItemGroup[$i]['Colour'] = $colour;
$stockItemGroup[$i]['RestVariant'] = $restVariant;
$stockItemGroup[$i]['NewItemName'] = createNewItemName($colour, $restVariant, $stockItem['StockItemName']);
}
I have tried both in a foreach and a for loop (I read that a foreach does some copying, so I thought that might cause it). but to no avail.
I have also obviously tried
$stockItem['Colour'] = $colour;
$stockItem['RestVariant'] = $restVariant;
$stockItem['NewItemName'] = createNewItemName($colour,
$restVariant,
$stockItem['StockItemName']);
But that did not change anything either.
I am a total Php noob, so it might be very obvious, any help would be appreciated.
EDIT:
this loop is inside a method which is called in this loop:
$stockItemGroups = getStockItemGroups();
foreach ($stockItemGroups as $stockItemGroup){
addVariants($stockItemGroup);
//writeNewGroup($stockItemGroup);
}
foreach ($stockItemGroups as &$stockItemGroup){ Pass the array as a reference – RiggsFolly

Fatal error: Can't use function return value in write context error in PHP

I need to get values of html element name 'item_name1','item_name2','item_name3'...so on using loop. But it is showing this fatal error. Please help to resolve...
Code is:
$item_name = array();
$item_qty = array();
$item_value = array();
for($i=1;$i<=php_count;$i++){
$item_name($i) = $_POST['item_name+$i'];
$item_qty($i) = $_POST['item_qty+$i'];
$item_value($i) = $_POST['item_value+$i'];
echo($item_name($i));
}
You need square brackets [ ] instead of parentheses ( ) when accessing your arrays. The former are used for array indexing while the latter are used for function calls.
Since you are essentially calling your array like a function and you have the result of that call on the left-hand side of an assignment, you are getting the error that you can't write to a function return value.
And by the way: Currently you are literally accessing the indexes item_name+$i and such of $_POST because you have the +$i part inside of the string. Use $_POST['item_name' + $i] instead.
as requested
use square brackets for array elements
use double quotes to allow variable processing within string context
use variable for php count
$item_name = array();
$item_qty = array();
$item_value = array();
for($i=1;$i<=$items_count;$i++){
$item_name[$i]= $_POST[“item_name+$i”];
$item_qty[$i] = $_POST[“item_qty+$i”];
$item_value[$i] = $_POST[“item_value+$i”];
echo($item_name[$i]);
}
———
alternative solution
simplify by changing your form input names to allow arrays of data
Input names such as item[0][name] would allow you to simply loop through an item array!
foreach($_POST['item'] as $item) {
$item_name = $item['name'];
...
Your code have to like this
$item_name[$i] = $_POST['item_name'.$i];
$item_qty[$i] = $_POST['item_qty'.$i];
$item_value[$i] = $_POST['item_value'.$i];
echo($item_name[$i]);

How do I execute a string as code in PHP?

I have a string stored in a database that I'm pulling into an array lets say for example the string is "$foo" what I'm trying to do is use that string as a php variable to be interpreted by php, but I can't seem to figure it out. I did try using eval, but I couldn't get that to work in my current code and from what I've read eval() is too dangerous to use in a live environment.
Here is a sample of my code
$result = $sql->query("SELECT * FROM newordersystem");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row);
foreach ($set as $item) {
$item[PHPVARIABLE] = stripslashes($_POST[$item[INPUTIDNAME]]);}
The last line is where my problem lies, in that I want "$item[PHPVARIABLE]" to execute as $foo so the result would end up being $foo = 1
Any help or advice would be greatly appreciated!
Strange architecture and I don't get 100% your goal, but if you need:
$item[$item[INPUTIDNAME]] = stripslashes($_POST[$item[INPUTIDNAME]]);}
or
${$item[PHPVARIABLE]} = stripslashes($_POST[$item[INPUTIDNAME]]);}

PHP - How to modify deeply nested associative arrays?

I'm having troubles building a deeply nested associative array in PHP. From the questions/answers I've seen here and there, I gathered I should use references but I just can't figure out how to do so.
I am using PHP 5.3
I'm parsing a file that looks like JSON. It contains nested "sections" enclosed in curly braces and I want to build up a tree representation of the file using nested associative arrays.
I'm starting with a root section and a "current section" variables:
$rootSection = array();
$currentSection = $rootSection;
$sections = array();
When I enter a new section ('{'), this is what I do:
$currentSection[$newSectionName] = array();
array_push($sections, $currentSection);
$currentSection = $currentSection[$newSectionName];
I use the $sections variable to pop out of a section ('}') into its parent one:
$currentSection = array_pop($sections);
And finally, when I want to add a property to my section, I basically do:
$currentSection[$name] = $value;
I've removed all attempt to use references from the above code, as nothing has worked so far...
I might as well say that I am used to Javascript, where references are the default...
But it's apparently not the case with PHP?
I've dumped my variables in my parsing code and I could see that all properties were correctly added to the same array, but the rootSection array or the one pushed inside $sections would not be updated identically.
I've been looking for a way to do this for a few hours now and I really don't get it...
So please share any help/pointers you might have for me!
UPDATE: The solution
Thanks to chrislondon I tried using =& again, and managed to make it work.
Init code:
$rootSection = array();
$currentSection =& $rootSection;
$sections = array();
New section ('{'):
$currentSection[$newSectionName] = array();
$sections[] =& $currentSection;
$currentSection =& $currentSection[$newSectionName];
Exiting a section ('}'):
$currentSection =& $sections[count($sections) - 1];
array_pop($sections);
Note that starting around PHP 5.3, doing something like array_push($a, &$b); is deprecated and triggers a warning. $b =& array_pop($a) is also not allowed; that's why I'm using the []=/[] operators to push/"pop" in my $sections array.
What I initially had problems with was actually this push/pop to my sections stack, I couldn't maintain a reference to the array and was constantly getting a copy.
Thanks for your help :)
If you want to pass something by reference use =& like this:
$rootSection = array();
$currentSection =& $rootSection;
$currentSection['foo'] = 'bar';
print_r($rootSection);
// Outputs: Array ( [foo] => bar )
I've also seen the syntax like this $currentSection = &$rootSection; but they're functionally the same.

Dynamically access an object property array element in PHP

I have an object, that I would like to interact with dynamically. I would like to rename the game1_team1 in:
$default_value = $individual_match->field_match_game1_team1[0]['value'];
to be game1_team2, game2_team1, game2_team2, game3_team1, etc. Based on the loop they are in.
I have tried:
$dynamic = 'field_match_game'.$i.'_team'.$j;
$default_value = $individual_match->$dynamic[0]['value'];
but it returns
Fatal error: Cannot use string offset
as an array
Update: Based on Saul's answer, I modified the code to:
$default_value = $individual_match->{'field_match_game'.$i.'_team'.$j}[0]['value'];
which got rid of the Fatal error, but doesn't return a value.
$individual_match->field_match_game1team1[0]['value'] = 'hello1';
$i = 1;
$j = 1;
$default_value = $individual_match->{'field_match_game'.$i.'team'.$j}[0]['value'];
'Renaming' is not possible unless you create a new property, and delete the old one.
Access dynamic names like this:
$dynamic = "field_match_$i_team$j";
$default_value = $individual_match->$dynamic[0]['value'];
Note the $ between -> and dynamic.
Delete and create example:
$oldProperty = "field_match_1_team1";
$newProperty = "field_match_$i_team$j";
$hold = $individual_match->$oldProperty;
unset($individual_match->$oldProperty);
$individual_match->$newProperty = $hold;
Look at this : http://php.net/manual/en/function.get-class-vars.php
You can list all object's properties in array and select only needed.

Categories