Lets say I need three arrays, ford, chevy and dodge. Each array has three items:
$ford['engine'] = 'something';
$ford['color'] = 'something';
$ford['price'] = 'something';
$chevy['engine'] = 'something';
$chevy['color'] = 'something';
$chevy['price'] = 'something';
$dodge['engine'] = 'something';
$dodge['color'] = 'something';
$dodge['price'] = 'something';
I can write that out no problem and it doesn't take too long. But, lets say I need fifty or sixty arrays that I need to make, all with ten to twenty different items. I want to put a variable at the top of each array's file to denote what the array name will be, but I am not quite clear on the syntax and I am not too familiar with $$ or how I would use that with arrays:
$name = 'ford';
$(I want this to be "$name")['engine'] = 'something';
$(I want this to be "$name")['color'] = 'something';
$(I want this to be "$name")['price'] = 'something';
I have also considered just doing this:
$name = 'ford';
$view[$name.'_engine']
$view[$name.'_color']
$view[$name.'_price']
Can I get some suggestions on the best way to approach this?
Write a small function to do that
$cars = array(); //Create an array to hold the values
function writeArray($car, $var1, $var2, $var3) {
global $cars;
$cars[$car] = array('engine' => $var1, 'color' => $var2, 'price' => $var2);
}
//Now use it like
writeArray('Chevy', $something, $something, $something);
//If you want to access the array in the form of $ford['engine'] then use this
extract($cars); //This will split the array into small array accessible by model
You can use variable variables:
$var = 'ford';
$$var['engine'] = '...';
$$var['color'] = '...';
$var = 'chevy';
$$var['engine'] = '...';
$$var['color'] = '...';
Or just use multidimensional array:
$cars = array();
$make = 'ford';
$cars[$make] = array();
$cars[$make]['engine'] = '...';
$cars[$make]['color'] = '...';
// or
$cars['ford'] = array(
'engine' => '...',
'color' => '...',
);
Related
I have a variable like:
foreach ($array as $data){
$namee=$data['Label_Field'];
${$namee} = $_POST[$namee];
}
How do I get a value like ("data", "data") using those variables?
you can use $$ in php
Example:
$a = 'name';
$$a = 'test';
echo $name;
Result:
test
Example of your code:
foreach ($array as $data){
$namee = $data['Label_Field'];
$$namee = $_POST[$namee];
}
I also suggest you read the following:
https://www.php.net/manual/en/language.variables.variable.php
https://www.geeksforgeeks.org/php-vs-operator/
https://www.javatpoint.com/php-dollar-doubledollar
what is "$$" in PHP
Avoid using variable variables, simply filter $_POST into a new variable, else there is a likely risk of overwriting important variables ($db_connection?).
Instead do some thing like:
<?php
$_POST['foo'] = '';
$_POST['bar'] = '';
$_POST['baz'] = '';
// fields
$fields = [['Label_Field' => 'foo']];
// just labels
$labels = array_column($fields, 'Label_Field');
// filter $_POST by keys which are in $labels
$data = array_filter($_POST, fn($k) => in_array($k, $labels), ARRAY_FILTER_USE_KEY);
print_r($data);
Then use $data['foo'] instead of $foo.
View online: https://3v4l.org/vna02
This is my current code, I'm looking for a more efficient way of writing it.
Need something like looping through each variable with a foreach or adding them all to an array somehow, without me having to re-write every variable name.
$formValues = $form_state->getValues();
$relocation = $formValues['relocation'];
$europe = $formValues['europe'];
$twoyears = $formValues['twoyears'];
$realestate = $formValues['realestate'];
$nominated = $formValues['check_nominated_by'];
$nom_comp = $formValues['nom_company'];
$nom_contact = $formValues['nom_contact'];
$nom_email = $formValues['nom_email'];
$contact1 = $formValues['contact1'];
$position1 = $formValues['contact_position1'];
$email1 = $formValues['email1'];
$contact2 = $formValues['contact2'];
$position2 = $formValues['contact2'];
$email2 = $formValues['contact2'];
$contact3 = $formValues['contact3'];
$position3 = $formValues['contact3'];
$email3 = $formValues['contact3'];
tempstore = array();
$tempstore['relocation'] = $relocation;
$tempstore['europe'] = $europe;
$tempstore['twoyears'] = $twoyears;
$tempstore['realestate'] = $realestate;
$tempstore['membertype'] = $membertype;
$tempstore['nominated_by'] = '';
// All other fields need to be in this array too
// But there are a lot of unwanted fields in the $formValues
$_SESSION['sessionName']['formName'] = $tempstore;
Seeing as you know the keys you'd like to keep you can do the following:
<?php
/** The keys you want to keep... **/
$keys_to_keep = [
];
/** Will be used to store values for saving to $_SESSION. **/
$temp_array = [];
/** Loop through the keys/values. **/
foreach ($formValues as $key => $value) {
/** The correct key i.e. the key you'd like to save. **/
if (in_array($key, $keys_to_keep)) {
/** What you wish to do... **/
$temp_array[$key] = $value;
}
}
$_SESSION['sessionName']['formName'] = $temp_array;
?>
What is happening is that you are looping through your $formValues and getting both the keys and values of each pair in the array.
Then an check is being done against your $keys_to_keep to see if the current element is the one you wish to keep, if it is then you save it in to $temp_array.
Reading Material
foreach
in_array
You can use variable variables and a foreach.
Foreach($formValues as $key => $var){
$$key = $var;
}
Echo $relocation ."\n" . $europe;
https://3v4l.org/QeLjp
Edit I see now that your array variable keys are not always the same as the variable name you want.
In that case you can't use the method above.
In that case you need to use list() = array.
List($relocation, $europe) = $formValues;
// The list variables have to be in correct order I just took the first two for demo purpose.
I have this array.
$test['color'][0] = "red";
$test['color'][1] = "blue";
$test['color'][2] = "black";
$test['plug'][3] = "US";
$test['plug'][4] = "UK";
i am trying to achieve this from above array.
$test2['color'] = "red,blue,black";
$test2['plug'] = "US,UK";
What would be the best logic to implement this.
You can use a little logic and a few PHP functions quite nicely:
<?php
$array['color'][0] = "red";
$array['color'][1] = "blue";
$array['color'][2] = "black";
$array['plug'][3] = "US";
$array['plug'][4] = "UK";
$test2=array();
foreach($array as $key=>$val)
{
$test2[$key]=implode(',',$val);
}
print_r($test2);
?>
Output:
Array
(
[color] => red,blue,black
[plug] => US,UK
)
Edit: First answer was wrong and overly complicated. This is a one control structure solution.
$test2['color'] = implode(',', $test['color']);
$test2['plug'] = implode(',', $test['plug']);
print_r($test2);
PHP has a function extract that will convert an array like this:
$array = array(
'var1' => 1,
'var2' => 2
);
to:
$var1 = 1;
$var2 = 2;
now, I need the opposite, i have few variables:
$var3 = 'test';
$test = 'another';
$datax = 1;
that needs to be:
$array = array(
'var3' => 'test',
'test' => 'another',
'datax' => 1
);
Is there something like this in PHP?
You can use compact() to achieve this.
$var3 = 'test';
$test = 'another';
$datax = 1;
$array = compact('var3', 'test', 'datax');
Reference: http://php.net/manual/en/function.compact.php
like this
$preDefined = (get_defined_vars());
$var3 = 'test';
$test = 'another';
$datax = "1";
$newDefined = array_diff(get_defined_vars(), $preDefined);
print_r($newDefined);
$array = get_defined_vars()
See get_defined_vars()
You'd have to be really sure you wanted to do this (it includes things in the global scope automatically) but you can use
$my_vars = get_defined_vars();
If you want it more selective than that, you could look at filtering it like this:
$my_vars = pack_vars(get_defined_vars())
function pack_vars ($defined_vars)
{
$packed = array();
$ignored = array('dont_use_this', 'ignored_var', 'ignore_this_too');
foreach ($defined_vars AS $key => $value)
{
if (!in_array($key, $ignored))
{
$packed[$key] = $value;
}
}
return $packed;
}
I have an array that I declare like this:
$health_array = array( );
For every iteration I try to put these 3 items in it like this:
$health_array["num_problems"] = $num_problems;
$health_array["category_id"] = $category_id;
$health_array["category_name"] = $category_name;
But when I loop through the array I get gibberish. Here is how I loop through it:
foreach ($health_array as $i => $row)
{
echo '<p>'.$row['category_name'].' '.$row['category_id'].' '.$row['num_problems'].'</p>';
}
Any idea what I am doing wrong?
Thanks!!
Your problem comes from the fact that you want to do a multi-dimensional array and you're creating a monodimensional one, by overwriting each time the same 3 elements.
You should do something like:
$health_array = array();
$tmp = array();
$tmp["num_problems"] = 5;
$tmp["category_id"] = 8;
$tmp["category_name"] = "something";
$health_array[] = $tmp;
$tmp["num_problems"] = 15;
$tmp["category_id"] = 22;
$tmp["category_name"] = "something else";
$health_array[] = $tmp;
foreach ($health_array as $h)
{
echo $h["num_problems"]." - ".$h["category_id"]." - ".$h["category_name"]."<br />";
}
For every iteration I try to put these 3 items in it like this:
$health_array["num_problems"] = $num_problems;
$health_array["category_id"] = $category_id;
$health_array["category_name"] = $category_name;
It looks like you meant to build your array like this instead:
$health_array[] = array(
"num_problems" => $num_problems,
"category_id" => $category_id,
"category_name" => $category_name
);
This makes an array of arrays, where previously you were overwriting the keys of the same array for each iteration.