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
Related
I have an array, I need to loop through and change it's value:
foreach ($input['qualification'] as &$_v) {
$_v = ucwords($_v);
}
But this only works for the first item in the array. When I remove the ampersand it loops through the entire array, but obviously the changes are not made.
If you're trying to apply a function to all of the values in an array I would recommend using array_map() instead.
Applies the callback to the elements of the given arrays
$qualifications = array_map('ucwords', $input['qualification']);
Demo
$input['qualification'] = array('high school', 'inter school', 'bachelor of scinece', 'master of science');
foreach ($input['qualification'] as &$_v) {
$_v = ucwords($_v);
}
echo "<pre>";print_r($input['qualification']);
Here is how to do it more slowly, with explicit reference to the index, in case your actual programming task requires the value of the index.
https://eval.in/436395
$input = array('juggling','french','math');
foreach ($input as $i=>$v) {
$input[$i] = ucwords($v);
}
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');
I am trying to unset/remove then replace/update a single value from a post meta field, but my code for array_push() and unset() are removing all of the values from each array.
Here are the two halves of the code I am currently using.
First, to find and remove the old value:
$ID = $_GET["post_id"];
$old = $entry["85"];
$old_meta = array();
$old_meta = get_post_meta($old,'_website',false);
if(in_array($ID, $old_meta[current][items])){
unset($old_meta[current][items][$ID]);
}
update_post_meta($old,'_website',$old_meta);
Second to append the new value to the appropriate location:
$port = $entry["24"];
$new_meta = array();
$new_meta = get_post_meta($port,'_website',false);
$new_meta[content][items] = array();
array_push($new_meta[content][items],$ID);
update_post_meta($port,'_website',$new_meta);
It works to unset and insert the correct value, but any other values that were there (for both updating or unsetting) in the meta[current][items] array are removed.
Before running any functions the array looks like this:
pastie.org/8112933
After I run array_push it looks like this:
pastie.org/8112956
After unset it looks like this:
pastie.org/8112974
in_array checks to see if an element in array has a value equal to that value, not a key. So you would need to do something like this:
if(in_array($ID, $old_meta['current']['items'])){
foreach($old_meta['current']['items'] as $key => $val) {
if($val == $ID) {
unset($old_meta['current']['items'][$key]);
}
}
}
If you need to check for a key not a value just replace in_array() with array_key_exists() and keep your current code.
i am trying to create array like in the example i wrote above:
$arr=array('roi sabah'=>500,yossi levi=>300,dana=>700);
but i want to create it dynamic with foreach.
how can i do it ?
thanks.
You can access an array with foreach (and optionally create another one while going through the array's values). But if you only have data like a name and a number from your example, not stored in an array, you can't use foreach.
Another way to create the array you mentioned:
$arr = array();
$arr['roi sabah'] = 500;
$arr['yossi levi'] = 300;
// etc
And to access these values:
foreach ($arr as $key => $value) {
// $key is e.g. "roi sabah", and its value "500"
}
I have an array that I want on multiple pages, so I made it a SESSION array. I want to add a series of names and then on another page, I want to be able to use a foreach loop to echo out all the names in that array.
This is the session:
$_SESSION['names']
I want to add a series of names to that array using array_push like this:
array_push($_SESSION['names'],$name);
I am getting this error:
array_push() [function.array-push]:
First argument should be an array
Can I use array_push to put multiple values into that array? Or perhaps there is a better, more efficient way of doing what I am trying to achieve?
Yes, you can. But First argument should be an array.
So, you must do it this way
$_SESSION['names'] = array();
array_push($_SESSION['names'],$name);
Personally I never use array_push as I see no sense in this function. And I just use
$_SESSION['names'][] = $name;
Try with
if (!isset($_SESSION['names'])) {
$_SESSION['names'] = array();
}
array_push($_SESSION['names'],$name);
$_SESSION['total_elements']=array();
array_push($_SESSION['total_elements'], $_POST["username"]);
Yes! you can use array_push push to a session array and there are ways you can access them as per your requirement.
Basics:
array_push takes first two parameters array_push($your_array, 'VALUE_TO_INSERT');.
See: php manual for reference.
Example:
So first of all your session variable should be an array like:
$arr = array(
's_var1' => 'var1_value',
's_var2' => 'var2_value'); // dummy array
$_SESSION['step1'] = $arr; // session var "step1" now stores array value
Now you can use a foreach loop on $_SESSION['step1']
foreach($_SESSION['step1'] as $key=>$value) {
// code here
}
The benefit of this code is you can access any array value using the key name for eg:
echo $_SESSION[step1]['s_var1'] // output: var1_value
NOTE: You can also use indexed array for looping like
$arr = array('var1_value', 'var1_value', ....);
BONUS:
Suppose you are redirected to a different page
You can also insert a session variable in the same array you created. See;
// dummy variables names and values
$_SESSION['step2'] = array(
's_var3' => 'page2_var1_value',
's_var4' => 'page2_var2_value');
$_SESSION['step1step2'] = array_merge($_SESSION['step1'], $_SESSION['step2']);
// print the newly created array
echo "<pre>"; // for formatting printed array
var_dump($_SESSION['step1step2']);
echo "<pre>";
OUTPUT:
// values are as per my inputs [use for reference only]
array(4) {
["s_var1"]=>
string(7) "Testing"
["s_var2"]=>
int(4) "2124"
["s_var3"]=>
int(4) "2421"
["s_var4"]=>
string(4) "test"
}
*you can use foreach loop here as above OR get a single session var from the array of session variables.
eg:
echo $_SESSION[step1step2]['s_var1'];
OUTPUT:
Testing
Hope this helps!
Try this, it's going to work :
session_start();
if(!isset($_POST["submit"]))
{
$_SESSION["abc"] = array("C", "C++", "JAVA", "C#", "PHP");
}
if(isset($_POST["submit"]))
{
$aa = $_POST['text1'];
array_push($_SESSION["abc"], $aa);
foreach($_SESSION["abc"] as $key => $val)
{
echo $val;
}
}
<?php
session_start();
$_SESSION['data']= array();
$details1=array('pappu','10');
$details2=array('tippu','12');
array_push($_SESSION['data'],$details1);
array_push($_SESSION['data'],$details2);
foreach ($_SESSION['data'] as $eacharray)
{
while (list(, $value) = each ($eacharray))
{
echo "Value: $value<br>\n";
}
}
?>
output
Value: pappu Value: 10 Value: tippu Value: 12