Related
Take a look at this code:
$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
I'm looking for something like this so that:
print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Is there a function to do this? (because array_push won't work this way)
Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.
You'll have to use
$arrayname[indexname] = $value;
Pushing a value into an array automatically creates a numeric key for it.
When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
You can use the union operator (+) to combine arrays and keep the keys of the added array. For example:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);.
There's more info on the usage of the union operator vs array_merge in the documentation at http://php.net/manual/en/function.array-merge.php.
I wonder why the simplest method hasn't been posted yet:
$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
I would like to add my answer to the table and here it is :
//connect to db ...etc
$result_product = /*your mysql query here*/
$array_product = array();
$i = 0;
foreach ($result_product as $row_product)
{
$array_product [$i]["id"]= $row_product->id;
$array_product [$i]["name"]= $row_product->name;
$i++;
}
//you can encode the array to json if you want to send it to an ajax call
$json_product = json_encode($array_product);
echo($json_product);
hope that this will help somebody
Exactly what Pekka said...
Alternatively, you can probably use array_merge like this if you wanted:
array_merge($_GET, array($rule[0] => $rule[1]));
But I'd prefer Pekka's method probably as it is much simpler.
I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.
I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.
Pretty easy & simple really
// Get All Settings
$settings=getGlobalSettings();
// Apply User Theme Choice
$theme_choice = $settings['theme'];
.. etc etc etc ....
function getGlobalSettings(){
$dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
$MySQL = "SELECT * FROM systemSettings";
$result = mysqli_query($dbc, $MySQL);
while($row = mysqli_fetch_array($result))
{
$settings[$row['item']] = $row['value']; // NO NEED FOR PUSH
}
mysqli_close($dbc);
return $settings;
}
So like the other posts explain... In php there is no need to "PUSH" an array when you are using
Key => Value
AND... There is no need to define the array first either.
$array=array();
Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.
I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!
This is the solution that may useful for u
Class Form {
# Declare the input as property
private $Input = [];
# Then push the array to it
public function addTextField($class,$id){
$this->Input ['type'][] = 'text';
$this->Input ['class'][] = $class;
$this->Input ['id'][] = $id;
}
}
$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');
When you dump it. The result like this
array (size=3)
'type' =>
array (size=3)
0 => string 'text' (length=4)
1 => string 'text' (length=4)
2 => string 'text' (length=4)
'class' =>
array (size=3)
0 => string 'myclass1' (length=8)
1 => string 'myclass2' (length=8)
2 => string 'myclass3' (length=8)
'id' =>
array (size=3)
0 => string 'myid1' (length=5)
1 => string 'myid2' (length=5)
2 => string 'myid3' (length=5)
A bit late but if you don't mind a nested array you could take this approach:
$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));
To clarify,
if you output json_encode($main_array) that will look like [{"Key":"10"}]
A bit weird, but this worked for me
$array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
$array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
$array3 = array();
$count = count($array1);
for($x = 0; $x < $count; $x++){
$array3[$array1[$x].$x] = $array2[$x];
}
foreach($array3 as $key => $value){
$output_key = substr($key, 0, -1);
$output_value = $value;
echo $output_key.": ".$output_value."<br>";
}
$arr = array("key1"=>"value1", "key2"=>"value");
print_r($arr);
// prints array['key1'=>"value1", 'key2'=>"value2"]
The simple way:
$GET = array();
$key = 'one=1';
parse_str($key, $GET);
http://php.net/manual/de/function.parse-str.php
Example array_merge()....
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
Array([color] => green,[0] => 2,[1] => 4,[2] => a,[3] => b,[shape] => trapezoid,[4] => 4,)
I wrote a simple function:
function push(&$arr,$new) {
$arr = array_merge($arr,$new);
}
so that I can "upsert" new element easily:
push($my_array, ['a'=>1,'b'=>2])
2023
A lot of answers. Some helpful, others good but awkward. Since you don't need complicated and expensive arithmetic operations, loops etc. for a simple operation like adding an element to an array, here is my collection of One-Liner-Add-To-Array-Functions.
$array = ['a' => 123, 'b' => 456]; // init Array
$array['c'] = 789; // 1.
$array += ['d' => '012']; // 2.
$array = array_merge($array, ['e' => 345]); // 3.
$array = [...$array, 'f' => 678]; // 4.
print_r($array);
// Output:
/*
Array
(
[a] => 123
[b] => 456
[c] => 789
[d] => 012
[e] => 345
[f] => 678
)
*/
In 99,99% i use version 1. ($array['c'] = 789;). But i like version 4. That is the version with the splat operator (https://www.php.net/manual/en/migration56.new-features.php).
array_push($arr, ['key1' => $value1, 'key2' => value2]);
This works just fine.
creates the the key with its value in the array
hi i had same problem i find this solution you should use two arrays then combine them both
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
reference : w3schools
For add to first position with key and value
$newAarray = [newIndexname => newIndexValue] ;
$yourArray = $newAarray + $yourArray ;
There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.
$intial_content = array();
if (true) {
$intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}
array_push($GET, $GET['one']=1);
It works for me.
I usually do this:
$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
So I have various arrays which do not always have the same key/value pairs in them. What I want to do is to be able to merge the arrays, but to add in empty key/value pairs if they don't already exist in that array, but do in others. It's hard to explain but this might explain it better:
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
I need to somehow turn this into:
$finalArray = array(
array('name' => 'rory', 'car' => 'opel', 'dog' => ''),
array('name' => 'john', 'car' => '', 'dog' => 'albert')
);
I have been looking through PHP's documentation but can't find anything that will do this for me. Can anyone point me in the right direction? I don't even know an appropriate search term for what I want to achieve here, "array merge" isn't specific enough.
<?php
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$diff1=array_diff(array_flip($arrayOne), array_flip($arrayTwo));
$diff2=array_diff(array_flip($arrayTwo), array_flip($arrayOne));
//array_flip flips the key of array with value
//array_diff would return the values in the first array that are not present in any of the other arrays inside
foreach ($diff2 as $s) {
$arrayOne[$s]="";
}
foreach ($diff1 as $s) {
$arrayTwo[$s]="";
};
//set key that didn't exist in that array as ""
$finalArray[]=$arrayOne;
$finalArray[]=$arrayTwo;
//add the arrays to the final array
print_r($finalArray);
Here's what I would do:
Merge your separate arrays into one (into a temporary var) using array_merge
Get the unique keys of this new array using array_keys
For each separate array, loop through the new keys array and add an empty value for each key that is not in the array. Then push the separate array into a final array.
<?php
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$new = array_merge($arrayOne,$arrayTwo);
$new = array_keys($new);
$newarray = array();
foreach($new as $value){
$newarray[0][$value] = isset($arrayOne[$value]) ? $arrayOne[$value] : '' ;
$newarray[1][$value] = isset($arrayTwo[$value]) ? $arrayTwo[$value] : '' ;
}
echo "<pre>";print_r($newarray);
You can also use this short answer
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$defaults = array('name' => '','car' => '','dog' => '');
$arrayOne += $defaults;
$arrayTwo += $defaults;
$newarray = array($arrayOne,$arrayTwo);
echo "<pre>";print_r($newarray);
Basing on what Justin Powell outlined, I managed to come up with this code before the other two code examples were posted (thank you mamta & user6439245).
I also needed to take the keys containing numbers and sort them appropriately, otherwise my keys would've been indexed like employer_1, education_1, employer_2, education_2.
// get the initial form entries data
$entries = array(
array('name' => 'john', 'car' => 'fiat', 'employer_1' => 'tangerine', 'education_1' => 'hideaways', 'education_2' => 'extras'),
array('name' => 'rory', 'car' => 'opel', 'employer_1' => 'sagittarius', 'employer_2' => 'tangerine', 'employer_3' => 'thehideout', 'education_1' => 'knatchbull')
);
// create an empty array to populate with all field keys
$mergedKeys = array();
// push all field keys into the array
foreach($entries as $entry){
foreach($entry as $key => $value){
array_push($mergedKeys, $key);
}
}
// remove duplicate keys from the array
$uniqueMergedKeys = array_unique($mergedKeys);
// create a new array to populate with the field keys we need to sort - the ones with numbers in
$keysToSort = array();
// push the number-containing keys into the array
$i=0;
foreach($uniqueMergedKeys as $uniqueKey){
if(1 === preg_match('~[0-9]~', $uniqueKey)){
array_push($keysToSort, $uniqueKey);
}
$i++;
}
// remove the number containing keys from the unique keys array
$uniqueMergedKeys = array_diff($uniqueMergedKeys, $keysToSort);
// sort the keys that need sorting
sort($keysToSort);
// put the newly sorted keys back onto the original keys array
foreach($keysToSort as $key){
array_push($uniqueMergedKeys, $key);
}
$final = array();
$i = 0;
foreach($entries as $entry){
foreach($uniqueMergedKeys as $key){
//if($entries[$i][$key]){
if (array_key_exists($key, $entries[$i])) {
$final[$i][$key] = $entries[$i][$key];
} else {
$final[$i][$key] = '';
}
}
$i++;
}
echo '<pre>'; print_r($final); echo '</pre>';
I have a PHP array like this:
$arr = array(
'id' => 'app.settings.value.id',
'title' => 'app.settings.value.title',
'user' => 'app.settings.value.user'
);
I want to remove '.id', '.title' and '.user' in the array values. I want to insert the key of this array at the end of the value. I know, that I can get an array key by passing an array and a value to 'array_search', but I want the key within this one array definition - at the end of it's value. Is this possible?
I don't like this, but I guess it's simple and works:
$arr = array(
'id' => 'app.settings.value',
'title' => 'app.settings.value',
'user' => 'app.settings.value'
);
$result = array();
foreach ($arr AS $key => $value) {
$result[$key] = $value . '.' . $key;
}
You're storing app.settings.value which is the same for all array items, so personally I'd prefer:
$arr = array(
'id',
'title',
'user'
);
function prepend_key($key)
{
return 'app.settings.value.' . $key;
}
$result = array_map('prepend_key', $arr);
With $result containing:
array(
'app.settings.value.id',
'app.settings.value.title',
'app.settings.value.user'
);
At the end of the day, either works :)
Take a look at this code:
$GET = array();
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */
I'm looking for something like this so that:
print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */
Is there a function to do this? (because array_push won't work this way)
Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.
You'll have to use
$arrayname[indexname] = $value;
Pushing a value into an array automatically creates a numeric key for it.
When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
You can use the union operator (+) to combine arrays and keep the keys of the added array. For example:
<?php
$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;
print_r($arr3);
// prints:
// array(
// 'foo' => 'bar',
// 'baz' => 'bof',
// );
So you could do $_GET += array('one' => 1);.
There's more info on the usage of the union operator vs array_merge in the documentation at http://php.net/manual/en/function.array-merge.php.
I wonder why the simplest method hasn't been posted yet:
$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
I would like to add my answer to the table and here it is :
//connect to db ...etc
$result_product = /*your mysql query here*/
$array_product = array();
$i = 0;
foreach ($result_product as $row_product)
{
$array_product [$i]["id"]= $row_product->id;
$array_product [$i]["name"]= $row_product->name;
$i++;
}
//you can encode the array to json if you want to send it to an ajax call
$json_product = json_encode($array_product);
echo($json_product);
hope that this will help somebody
Exactly what Pekka said...
Alternatively, you can probably use array_merge like this if you wanted:
array_merge($_GET, array($rule[0] => $rule[1]));
But I'd prefer Pekka's method probably as it is much simpler.
I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.
I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.
Pretty easy & simple really
// Get All Settings
$settings=getGlobalSettings();
// Apply User Theme Choice
$theme_choice = $settings['theme'];
.. etc etc etc ....
function getGlobalSettings(){
$dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
$MySQL = "SELECT * FROM systemSettings";
$result = mysqli_query($dbc, $MySQL);
while($row = mysqli_fetch_array($result))
{
$settings[$row['item']] = $row['value']; // NO NEED FOR PUSH
}
mysqli_close($dbc);
return $settings;
}
So like the other posts explain... In php there is no need to "PUSH" an array when you are using
Key => Value
AND... There is no need to define the array first either.
$array=array();
Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.
I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!
This is the solution that may useful for u
Class Form {
# Declare the input as property
private $Input = [];
# Then push the array to it
public function addTextField($class,$id){
$this->Input ['type'][] = 'text';
$this->Input ['class'][] = $class;
$this->Input ['id'][] = $id;
}
}
$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');
When you dump it. The result like this
array (size=3)
'type' =>
array (size=3)
0 => string 'text' (length=4)
1 => string 'text' (length=4)
2 => string 'text' (length=4)
'class' =>
array (size=3)
0 => string 'myclass1' (length=8)
1 => string 'myclass2' (length=8)
2 => string 'myclass3' (length=8)
'id' =>
array (size=3)
0 => string 'myid1' (length=5)
1 => string 'myid2' (length=5)
2 => string 'myid3' (length=5)
A bit late but if you don't mind a nested array you could take this approach:
$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));
To clarify,
if you output json_encode($main_array) that will look like [{"Key":"10"}]
A bit weird, but this worked for me
$array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
$array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
$array3 = array();
$count = count($array1);
for($x = 0; $x < $count; $x++){
$array3[$array1[$x].$x] = $array2[$x];
}
foreach($array3 as $key => $value){
$output_key = substr($key, 0, -1);
$output_value = $value;
echo $output_key.": ".$output_value."<br>";
}
$arr = array("key1"=>"value1", "key2"=>"value");
print_r($arr);
// prints array['key1'=>"value1", 'key2'=>"value2"]
The simple way:
$GET = array();
$key = 'one=1';
parse_str($key, $GET);
http://php.net/manual/de/function.parse-str.php
Example array_merge()....
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
Array([color] => green,[0] => 2,[1] => 4,[2] => a,[3] => b,[shape] => trapezoid,[4] => 4,)
I wrote a simple function:
function push(&$arr,$new) {
$arr = array_merge($arr,$new);
}
so that I can "upsert" new element easily:
push($my_array, ['a'=>1,'b'=>2])
2023
A lot of answers. Some helpful, others good but awkward. Since you don't need complicated and expensive arithmetic operations, loops etc. for a simple operation like adding an element to an array, here is my collection of One-Liner-Add-To-Array-Functions.
$array = ['a' => 123, 'b' => 456]; // init Array
$array['c'] = 789; // 1.
$array += ['d' => '012']; // 2.
$array = array_merge($array, ['e' => 345]); // 3.
$array = [...$array, 'f' => 678]; // 4.
print_r($array);
// Output:
/*
Array
(
[a] => 123
[b] => 456
[c] => 789
[d] => 012
[e] => 345
[f] => 678
)
*/
In 99,99% i use version 1. ($array['c'] = 789;). But i like version 4. That is the version with the splat operator (https://www.php.net/manual/en/migration56.new-features.php).
array_push($arr, ['key1' => $value1, 'key2' => value2]);
This works just fine.
creates the the key with its value in the array
hi i had same problem i find this solution you should use two arrays then combine them both
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
reference : w3schools
For add to first position with key and value
$newAarray = [newIndexname => newIndexValue] ;
$yourArray = $newAarray + $yourArray ;
There are some great example already given here. Just adding a simple example to push associative array elements to root numeric index index.
$intial_content = array();
if (true) {
$intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}
array_push($GET, $GET['one']=1);
It works for me.
I usually do this:
$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
I have two arrays:
array (
'AK_AGE_ASS_VISIBLE' => '1',
'AK_AGE_ASS_COMP' => '0',
.....
)
I want to change the key to another value taking it from another array:
array(
'AK_AGE_ASS_VISIBLE' => 'AGENT_ASSOCIATED',
'AK_AGE_ASS_COMP' => 'AGENT_ASSOCIATED_O',
....
)
The ending array should produce this array:
array(
'AGENT_ASSOCIATED' => '1',
'AGENT_ASSOCIATED_O' => '0',
...
)
What is the correct way to do these kind of things? Please note that the arrayys won't have the same number of entries and there is no warranty that the first array will have a corresponding key in the other array.
Thank you very much
Try this:
$values = array(
'AK_AGE_ASS_VISIBLE' => '1',
'AK_AGE_ASS_COMP' => '0',
// …
);
$keymap = array(
'AK_AGE_ASS_VISIBLE' => 'AGENT_ASSOCIATED',
'AK_AGE_ASS_COMP' => 'AGENT_ASSOCIATED_O',
// …
);
$output = array();
foreach ($values as $key => $val) {
$output[$keymap[$key]] = $val;
}
Use built-in array_combine()? http://www.php.net/manual/en/function.array-combine.php
You probably need to use array_intersect_key() to filter out those keys that don't exist in either on of the arrays. http://www.php.net/manual/en/function.array-intersect-key.php
Here is a magical one-liner:
$output = array_combine(
array_intersect_key($array_with_keys, $array_with_values),
array_intersect_key($array_with_values, $array_with_keys));