How to create a dynamic array variable - php

I have these arrays and i want to loop through every array by creating a dynamic variable that put their name in foreach loop automatically something like this
foreach ($activities.$i as &$activity) { //$i = 1,2,3,4..
//code
}
//activities
$activities1 = $_POST["activities1"];
$activities2 = $_POST["activities2"];
$activities3 = $_POST["activities3"];
$activities4 = $_POST["activities4"];

Easier method is to simply use the array naming hack:
<input name="activities[1]" ..>
<input name="activities[2]" ..>
<input name="activities[3]" ..>
which makes $_POST['activities'] you array:
foreach($_POST['activities'] as $i => $value) {
// $i -> 1,2,3,4
}
But if you insist on embedding the index inside the key's name, then:
foreach(range(1,4) as $i) {
foreach($_POST["activities{$i}"] as $value) {
...
}
}

Related

How to declare, insert and iterate a php associative array with an associative array as value?

I need to work with a hashtable which values can store variables like:
$numberOfItems
$ItemsNames
If I ain't wrong, that would mean another hash like array as value.
What should be the right syntax for inserting and iterating over it?
Is anything like:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
valid?
if there's no chance to have collusion in item name, you can use the name in key
$hash[$ItemsName] = $numberOfItems;
in the other case, use an integer for example as a key, then the different "attributes" you want as keys for the 2nd array
$hash[$integer]["count"] = $numberOfItems;
$hash[$integer]["name"] = $name;$
Then, for iterating (1st case):
foreach ($hash as $name => $number) {
echo $number;
echo $name;
}
or, 2nd case
foreach ($hash as $item) {
echo $item["name"];
echo $item["count"];
}
To create php array, which can be a hash table, you can do:
$arr['element'] = $item;
$arr['element'][] = $item;
$arr['element'][]['element'] = $item;
Other way:
$arr = array('element' => array('element' => array(1)));
To iterate over it use foreach loop:
foreach ($items as $item) {
}
It's also possible to create nested loops.
About your case:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
I would do:
$hash['anyKey']['numberOfItems'] = 15;
$hash['anyKey']['ItemsNames'] = array('f','fw');

Get the ids and loop through post data

I post a form with the same input names+id at the end like that:
<input type="text" name="machine_1">
<input type="text" name="machine_11">
<input type="text" name="machine_23">
How loop through on each of them and get the id's in the loop?
I tried this way, but it will loop a lot without any data and what happens if there is more thank 100 id?
for($i=0; $i<100; $i++){
$_POST["machine"]=$_POST["machine_".$i];
$id=$i;
}
POST is an associate array, so you can loop through everything that's been posted like this:
//$k contains the id
//$v contains the submitted value
foreach($_POST as $k => $v) {
//test if id contains 'machine'
if(stristr($k, 'machine')) {
echo $v;
}
}
You can do this using a foreach loop, like so:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value';
}
$_POST["machine"]=$_POST["machine_".$i];
here $_POST['machine'] represents noting..how can you assign a value to $_POST['machine']..you havent passed any element having name machine while submitting the form..so first of all you need to check it bro
In your code, you have:
$_POST["machine"]=$_POST["machine_".$i];
That's not the correct way. You want to store the value of $_POST["machine_".$i] to $id and then use it below.
This is probably what you need:
for($i=1; $i<100; $i++){
$id = $_POST["machine_".$i];
echo $id;
}
And if there are more than 100 elements, and you don't know the number of inputs, then you can use a foreach loop, as below:
$i = 1; // counter variable
foreach ($_POST as $key => $input) {
if($key == "machine_".$i) {
$id = $input; // or simply 'echo $input'
echo $id;
}
$i++; // increment counter
}

Getting the name of an array dynamically

I have an array which looks like this:
$example = [
['rendered'][0]['rendereditem1']
['rendered'][4]['rendereditem2 and more']
['rendered'][2]['rendereditem3']
]
Now I want to iterate with foreach to get the contents of 0,4,2!
Normally I would write:
foreach($example as $value){
print $value['rendered'][int which is the same everywhere];
}
But that is obviously not working because the array name is always different...how could I iterate in this case?
Simply add a second loop to iterate over the members :
foreach($example as $value) {
foreach($value['rendered'] as $key=>$item) {
// Do what you want here, $key is 0,4,2 in your example
}
}

Set value to each element of array of elements in zend

In my zend application i have a form that contains an array of elements like that:
ini1[0]
ini1[1]
...
To get they values i use:
$value = $form->ini1->getValue();
echo $value[0];
echo $value[1];
...
But i don't know how to set values to each elements of this array.
There's any way?
================================================================================
Code of element creation
$element['ini1'] = new Zend_Form_Element_Text('ini1');
$element['ini1']->setAttrib('maxLength', '5')
->setAttrib('class', 'horaTurno')
->setValue('00:00');
I'm creating a manual form, so in my form.phtml i have a for loop that create 7 elements like this:
for($i = 0; $i < 7; $i++){
echo $this->form->ini1
->setAttrib('name', 'ini1['. $i .']')
->setAttrib('id', 'ini1['. $i .']');
}
With a foreach-loop (PHP.net: foreach) you can iterate over your array and set a value on each item:
foreach($value as $item) {
$item->setValue('yourValue');
}

creating variable names from an array list

How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
//create a new variable called $elem1 (or $other or $elemother, etc.)
//and assign it some default value 1
}
foreach ($myarray as $name) {
$$name = 1;
}
This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.
goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:
extract(array_flip($myarray));
This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:
echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'
Wildly useful.
Something like this should do the trick
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
$myVars[$arr] = 1;
}
Extract ( $myVars );
What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).
Use array_keys($array)
i.e.
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
$myarray[$singleKeyName] = 1;
}
http://www.php.net/manual/en/function.array-keys.php

Categories