Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge variables into an array while retaining the variable name as key

Tags:

arrays

php

I have an array:

$countries = array( 
 "af" => "Afghanistan",
 "ax" => "Åland Islands",
 "al" => "Albania",
 "dz" => "Algeria"
);

and some variables:

$as = "American Samoa";
$ad = "Andorra";

How do I combine the variables into the array while keeping the variable name as the key in the array?

like image 533
Question Overflow Avatar asked Aug 17 '12 10:08

Question Overflow


People also ask

How do I merge two arrays with the same key?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

How do you use a variable as part of an array name?

Instead of having so many similar variables, you should use an array, or in your case an array of arrays: var myVariableArray = new double[][] { c[0], c[1], ... }; Now you can easily acces the i-th number within that array: double a = myVariableArray[i][i];

How do you add variables to an array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

Can a variable hold an array?

An array is a variable containing multiple values. Any variable may be used as an array. There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Arrays are zero-based: the first element is indexed with the number 0.


1 Answers

You can use compact to create an array out of your variables and then simply add the two arrays together:

$countries += compact('as', 'ad');

See it in action.

like image 146
Jon Avatar answered Oct 14 '22 08:10

Jon