array_push() with key value pair - php

I have an existing array to which I want to add a value.
I'm trying to achieve that using array_push() to no avail.
Below is my code:
$data = array(
"dog" => "cat"
);
array_push($data['cat'], 'wagon');
What I want to achieve is to add cat as a key to the $data array with wagon as value so as to access it as in the snippet below:
echo $data['cat']; // the expected output is: wagon
How can I achieve that?

So what about having:
$data['cat']='wagon';

If you need to add multiple key=>value, then try this.
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));

$data['cat'] = 'wagon';
That's all you need to add the key and value to the array.

You don't need to use array_push() function, you can assign new value with new key directly to the array like..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)

For Example:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
For changing key value:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
output:
Array ( [firstKey] => changedValue [secondKey] => secondValue )
For adding new key value pair:
$data['newKey'] = 'newValue';
//this will add new key and value because newKey is not available in array
output:
Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey]
=> newValue )

Array['key'] = value;
$data['cat'] = 'wagon';
This is what you need.
No need to use array_push() function for this.
Some time the problem is very simple and we think in complex way :) .

<?php
$data = ['name' => 'Bilal', 'education' => 'CS'];
$data['business'] = 'IT'; //append new value with key in array
print_r($data);
?>
Result
Array
(
[name] => Bilal
[education] => CS
[business] => IT
)

Just do that:
$data = [
"dog" => "cat"
];
array_push($data, ['cat' => 'wagon']);
*In php 7 and higher, array is creating using [], not ()

Related

PHP rename key in Associative array

I've been searching through the articles on SO for this question and tried many of the solutions in my own code but it's not seeming to work.
I have the following array
$array[] = array("Order_no"=>$order_id,
"Customer"=>$customer_id,
"Product"=>$code_po,
"Product_description"=>$code_description,
"Position"=>$pos,
"Qty"=>$item_qty
);
I am looking to replace the "Order_no" key with a variable from a database query, lets assume in this case the variable is "new_name"
$new = "new_name";
$array[$new]=$array["Order_no"];
unset($array["Order_no"]);
print_r($array);
in the print_r statement I am getting the new_name coming through as the correct order number, but I am still seeing "Order_no" there also, which I shouldn't be seeing anymore.
Thanks.
This is your array:
Array
(
[0] => Array
(
[Customer] => 2
[Product] => 99
[Order_no] => 12345
)
)
One way to do it:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$i_arr = $arr[0];
$i_arr["new_name"] = $i_arr["Order_no"];
unset($i_arr["Order_no"]);
$arr[0] = $i_arr;
print_r($arr);
Another way:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$arr[0]["new_name"] = $arr[0]["Order_no"];
unset($arr[0]["Order_no"]);
print_r($arr);
To flatten your array out at any time:
<?php
$arr = $arr[0];
print_r($arr);
You are using extra level of array (by doing $array[] = ...).
You should do it with [0] as first index as:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
Live example: 3v4l
Another option is get ride of this extra level and init the array as:
$array = array("Order_no"=>$order_id, ...
As $array is also an array, you have to use index:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
The other answers will work for the first time you add to the array, but they will always work on the first item in the array. Once you add another it will not work, so get the current key:
$array[key($array)][$new] = $array[key($array)]["Order_no"];
unset($array[key($array)]["Order_no"]);
If you want the first one, then call reset($array); first.
Change your variable to
$array=array("Order_no"=>$order_id,"Customer"=>$customer_id,"Product"=>$code_po,"Product_description"=>$code_description,"Position"=>$pos,"Qty"=>$item_qty);
or change your code to
$new = "new_name";
$array[0][$new]=$array[0]["Order_no"];
unset($array["Order_no"]);
print_r($array);
Just be careful this would change the order of the array

PHP Dynamic Nested Associative Array

I have an associative array which is generated dynamically with the values from database. When I print the whole array, it gives something like this when we put print_r($array).
Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )
When I echo like this,
echo $array['95a5c80811239526fb75cbf31740cc35']['product_id'];
it gives me product id.
But the problem is, the code '95a5c80811239526fb75cbf31740cc35' changes dynamically everytime. I want to echo the product id irrespective of this code.
I tried
$array[]['product_id'];
$array['']['product_id'];
But not working. Can anyone help me? Please ask me if you have any doubts.
You can use reset() in this case:
$array = array(
'95a5c80811239526fb75cbf31740cc35' => array( // dynamic
'product_id' => 2324
),
);
$value = reset($array); // set pointer to first element
echo $value['product_id']; // 2324
Assuming that the code is always the first element in the array:
$array[0]['product_id'];
If you collectively want all of the product ID's:
foreach($array as $product){
$productIds[] = $product['product_id'];
}
// $productIds is now what $array was, but without the codes, so the product_id's are the first elements.
You can use for each for this so that you can get the value of product Id
$array = Array ( [95a5c80811239526fb75cbf31740cc35] => Array ( [product_id] => 2324) )
foreach($array as $product){
echo $product['product_id'];
}
This would get your desired o/p
IF you are getting problem using Associative array then you can first convert it into numeric as follows
$arr=array( 'first' => array( 'product_id' => 2324) );
$arrr=array_values($arr);
echo $arrr[0]['product_id'];
Output:
2324
Hope this helps and to know about array_values go here
Depending on your situation, there are few possible solutions:
$array = array_shift(array_values(
Array(
'95a5c80811239526fb75cbf31740cc35' =>
Array(
'product_id' => 2324
)
)));
echo $array['product_id']; // 2324
Another solution, probably more efficient:
echo array_shift(array_slice($array, 0, 1)); // 2324
For PHP 5.4+ you could go with:
echo array_values($array)[0]; // 2324
$array[0]['product_id'];
Should do the trick.

How to insert an array to an array

I would like to add an array to within an existing array.
I am tryin to use array_push which works as long as i dont try to assign a key to the array (if i try to add a key i get a syntax error... :-()
This is my initial array:
$ResultArray = array(
"TransactionDate" => "$TransactionDate",
"tx"=>array(
"0"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" => "$PaymentConfirmedCount"
),
"1"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" => "$PaymentConfirmedCount"
)
)
);
i would then like to add:
$ArrayTOAdd = array(
"0"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" =>
"$PaymentConfirmedCount"
)
);
if I try:
array_push($ResultArray->tx, $ArrayTOAdd);
BUT this does not work and results in a warning of "array_push() [function.array-push]: First argument should be an array"
if i try this :
array_push($ResultArray, $ArrayTOAdd);
it just adds the array but not to $ResultArray->tx
Any suggestions would be greatly welcomed!
You have to access the element in the array with $ResultArray["tx"] and not $ResultArray->tx. The second one is for the access to members in a php class. So an
array_push($ResultArray["tx"], $ArrayTOAdd);
should work.

Percentages in key of an array

I'm currently reading through some code in a drupal module and have come across the following in an associative array.
$this->replacements = array(
'%field' => $this->instance['label'],
'%bundle' => $bundles[$this->instance['entity_type']][$this->instance['bundle']]['label'],
);
What does the % in the key mean or is it just a string label
I think its just sting label.
$a = array("%name" => "pugazh", "vaalue" => "value");
print_r($a);
If you try like this in corephp it will return an output like this
Array ( [%name] => pugazh [vaalue] => value )
But i don't know what its mean in drupal.

Best way to refer index which contains in array

In php I'm willing to check the existence of indexes that match with another values in array.
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
MY ideal result is, in this case, to get "form" and "date". Any idea?
Try
$fields_keys = array_keys($fields);
$fields_unique = array_diff($fields_keys, $indexes);
The result will be an array of all keys in $fields that are not in $indexes.
You can try this.
<?php
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
$b = array_diff(array_keys($fields), $indexes);
print_r($b);
You can use array_keys function to retrieve keys of a array
Eg:
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
Outputs
Array
(
[0] => 0
[1] => color
)
PHP Documentation
Your question is a little unclear but I think this is what you're going for
array_keys(array_diff_key($fields, array_fill_keys($indexes, null)));
#=> Array( 0=>"form", 1=>"date" )
See it work here on tehplayground.com
array_keys(A) returns the keys of array A as a numerically-indexed array.
array_fill_keys(A, value) populates a new array using array A as keys and sets each key to value
array_diff_key(A,B) returns an array of keys from array A that do not exist in array B.
Edit turns on my answer got more complicated as I understood the original question more. There are better answers on this page, but I still think this is an interesting solution.
There is probably a slicker way than this but it will get you started:
foreach(array_keys($fields) as $field) {
if(!in_array($field, $indexes)) {
$missing[] = $field;
}
}
Now you will have an array that holds form and date.

Categories