How to dynamicly set a array variable? - php

I have a problem with this code:
$a['i'] = 1;
$b = '$a[\'i\']';
echo $$b;
It display an error:
Notice: Undefined variable: $a['i'] in test.php on line 6
Is it possible to create dynamic array variable?
Thanks for your time.
EDIT: In my example I am trying to edit an multidimensional array. There is a problem when I try to add data to my array (JSON). I don't have fixed dimension of array, it my be 2 or more dimension (I am building a model for Web form, and I want to add invalid value to JSON).
Now in one of the methods of Web form object I have code which checks repopulation object to add invalid value if needed.
I can not just add a value to JSON array, I need to edit it on multidimensional level.
For now I came up on solution to dynamically generate variable name and, then, edit it. If someone have solution it will be appreciated.
private $form = array(
'form_contact'=>array(
'attr'=>array('tag'=>'FORM', 'method'=>'post'),
'elem'=>array(
'fs_contact'=>array(
'attr'=>array('legend'=>'Kontakt', 'tag'=>'FSET'),
'elem'=>array(
'name'=>array(
'attr'=>array('SPAN'=>'Ime i prezime', 'title'=>'Unesite Vaše ime i prezime', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('req'=>'noscript', 'length'=>255),
'invalid'=>true), // Holds info that this is invalid
'www'=>array(
'attr'=>array('SPAN'=>'Web sajt', 'title'=>'Unesite Vaš sajt', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('length'=>255)),
'email'=>array(
'attr'=>array('SPAN'=>'E-mail', 'title'=>'Unesite Vaš email', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('req'=>'email', 'length'=>255)),
'message'=>array(
'attr'=>array('SPAN'=>'Poruka', 'cols'=>'60', 'rows'=>'5', 'title'=>'Unesite Vašu poruku', 'tag'=>'TEXTA', 'value'=>'nesto'),
'validat'=>array('req'=>'all')),
'submit_new_contact_form'=>array(
'attr'=>array('tag'=>'INPUT', 'type'=>'submit', 'value'=>'Pošalji poruku!'))
))// FS end
)) // Form end
);// Array end

You can't do it that way, as PHP thinks you're looking for a variable with the name $a['i'], rather than the 'i' key in the $a array.
The proper, and conventional, way is to use a dynamic key/index instead:
$b = 'i';
echo $a[$b];

Related

Undefined offset when removing input field that is not the last one

I am using this HTML and JQuery code to add input fields:
https://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery
with a few changes, my code resembles this, shortened:
$(wrapper).append('<?php echo $this->Form->input("ticket.' +index+ '.startdate"); ?>');
where index is a var that I'm incrementing and decrementing when the add field or remove field buttons are being selected.
The problem is when I remove an element that is not the last one, for example:
I remove text 1, 2, or 3 and then submit it, I get the Undefined offset error, naturally, since the index var of the created elements stays the same, and the server gets
ticket.0.startdate
ticket.2.startdate
ticket.3.startdate
and has no idea where the ticket.1.startdate is.
PHP code:
$festivalticket = $this->Festivaltickets->newEntity();
if ($this->request->is('post')) {
$festivalticket = $this->Festivaltickets->patchEntity($festivalticket, $this->request->data, [
'associated' => [
'Tickets'
]
]);
}
I want to know if there's a way to get past this.
Thank you.
Us an array for your form fields. ticket_startdate[] will dynamically append array elements, so something like:
$(wrapper).append('<?php echo $this->Form->input("ticket_startdate[]"); ?>');
Then just loop through without worrying about the index:
foreach($_POST['ticket_startdate'] as $key => $start_date) {
echo "index $key is $start_date";
}
I can't tell what's going on with the PHP you posted. It looks like a framework so it may handle the array correctly.

PHP: Getter and Setter while using Arrays?

I'm extremely new to php so excuse my code if you think it is a mess but I've been trying to figure this out for hours.
I am trying to use the getter and setter method to pull functionality from a class then use an array to create new objects based off the class. $_GET is to get the input foodNumber from a HTML form which determines which position in the array is chosen. So if 0 is inputted on the form, it represents Salad, if 2 is entered on the form it should mean Vegetables.
So in my mind, the $foodObject is creating a new object from the class FoodArray. I am trying to make the objects be in an array, so in this case $foodArray. But I don't know how to input values through an array using the getter setter method using the class functions or how to call them.
Thanks in advance!
<?php
class FoodArray {
private $foodValue;
public function setFoodValue($x){
$this->foodValue=$x;
}
public function getFoodValue(){
return $this->foodValue;
}
}
$foodNumber = $_GET['foodNumber'];
$foodObject = new FoodArray;
$foodArray = array ("Salad", "Vegetables", "Pasta", "Pizza", "Burgers");
$foodArray=$foodObject->getFoodValue();
echo "The number you chose is ". $foodNumber;
echo "The food item you choose is".$foodArray[$foodNumber];
?>
/////HTML FORM/////
<html>
<body>
<form action="class_with_getter_and_setter.php" method="get">
<b>Choose a number between 0-4 and get a mystery food!</b>
<input type="text" name="foodNumber">
<input type="submit">
</form>
</body>
</html>
I'm not exactly sure what your final intention is but I can try to point out a couple of places where you are going wrong:
The setFoodValue() method of the FoodArray object is never called so $foodValue has no value
$foodArray is set as an array but is immediately overwritten when you call the line $foodObject->getFoodValue()
$foodObject->getFoodValue() actually returns nothing because $foodValue was never set
There should be no difference in your getters and setters if you are passing an array or a string you could pass them and retrieve them the same way.
Again not sure exactly what you are trying to accomplish but you could try something like this:
$foodObject = new FoodArray;
$foodArray = array ("Salad", "Vegetables", "Pasta", "Pizza", "Burgers");
$foodObject->setFoodValue($foodArray);
$foodObjectArray = $foodObject->getFoodValue();
echo "The number you chose is ". $foodNumber;
echo "The food item you choose is".$foodObjectArray[$foodNumber];
If the problem is that echo "The food item you choose is".$foodArray[$foodnumber]; doesn't produce what you expect, there are two potential problems:
I'm not clear on the intent of your $foodObject. However, the $foodArray=$foodObject->getFoodValue(); may be messing it up, unless the internal $foodValue property is (like) the $foodArray you declare with Salad, Vegetables, etc.
When echo-ing $foodArray[$foodnumber], the 'n' in number is lowercase where above you set $foodNumber (capital 'N')

Passing a dynamic variable in an array within PHP

I am not sure if it's possible or not but I am trying to pass a random variable to fill an array.
Here is the code normally:-
//Loading all data of user in an array variable.
$user_fields = user_load($user->uid);
// Updated one array variable in this array.
$user_fields -> field_module_3_status['und'][0]['value'] = "Started";
// Saved back the updated user data
user_save($user_fields);
But I want to provide the variable field_module_3_status dynamically through a variable.
Hence suppose I have $user_field_name = field_module_3_status.
So what I tried to do is:-
$user_fields = user_load($user->uid);
$this_users_status = $user_fields -> $user_field_name;
$this_users_status['und'][0]['value'] = "Started";
user_save($user_fields);
Unfortunately this doesn't work.
Any idea how I can achieve this?
You're making a copy of the array when you do the assignment to $this_users_status. You need to assign to the array in the object property.
$user_fields->{$user_field_name}['und'][0]['value'] = "Started";
Or you could use a reference:
$this_users_status =& $user_fields->$user_field_name;

How to pass an array using $_POST?

I know there are some similar questions but none of them solves my issue.
I have a simple form:
<form method="post">
Import data: <textarea type="text" name="import"></textarea>
<input type="submit">
</form>
Then I get data from the "import" field:
$current = my_data();
$import = $_POST['import'];
$merge = array_merge($current,$import);
The problem is, even if I paste:
array('foo' => 'bar')
I get:
Warning: array_merge(): Argument #2 is not an array in
(address)
on line (line)
I can't change the HTML markup and I have to paste arrays there. Any ideas how to fix it? I've been reading about serialize() but not sure if there's anything to serialize is array() is not array() for PHP. Why is that? Any solutions? Thanks a lot!
UPDATE
$current hold an array of options for my theme.
$merge is supposed to hold the same keys with different values (around 30-50 of them, not multidimensional but might be in the future), but of course users might add new ones so in order to ignore them I'm actually using:
$imported_options = array_merge($current_options , array_intersect_key($_POST["import"], $current_options ));
(simplified this one as it's just an example)
So after all I want to load an array from the form and update the other array with it.
PHP will not create arrays in $_GET/$_POST unless you tell it to:
Import data: <textarea type="text" name="import[]"></textarea>
^^---- need these
Without the [], PHP will treat any duplicate field names as strings to be overwritten. With [] in the name, PHP will treat them as new elements in an array.
You can do
$current['import'] = $import;
Or you can change your html this way:
<textarea type="text" name="myarray['import']"></textarea>
And in php:
$import = $_POST['myarray'];
The second argument is not an array.
$_POST['import'] = value received from the form.
With that said, try:
$current [] = $_POST['import'];
What are you trying to get from $_POST['import'] ?
you are using a textarea to get an array?
if it's just a single variable then use array_push
http://php.net/manual/es/function.array-push.php
for array_merge you need to have 2 arrays.

Acessing an multidimentional array from a variable

I want to store the parents keys of an array so I can access it later.
Something like:
$arr['hello'][0]['world'] = 'a';
$arr['hello'][1]['world'] = 'b';
And store both hello, 0 and world as some kind of variable so I can access the array with it:
For example, something I would think it may work is:
$indexes = array('hello', 0, 'world');
$arr[$indexes]
But this doesn't work, as an array is an illegal offset type for another array. So is there a way to access an array by an array of parents keys (variable)?
i think you want
echo $array[{$one}][{$two}];
So do you want to access a child array by a custom key that occurs in a parent array?
$parent_array[$custom_key] = array('hello',0,'world');

Categories