Prepend associative array elements to an associative array - php

Is it possible to prepend an associative array with literal key=>value pairs? I know that array_unshift() works with numerical keys, but I'm hoping for something that will work with literal keys.
As an example I'd like to do the following:
$array1 = array('fruit3'=>'apple', 'fruit4'=>'orange');
$array2 = array('fruit1'=>'cherry', 'fruit2'=>'blueberry');
// prepend magic
$resulting_array = ('fruit1'=>'cherry',
'fruit2'=>'blueberry',
'fruit3'=>'apple',
'fruit4'=>'orange');

Can't you just do:
$resulting_array = $array2 + $array1;
?

You cannot directly prepend an associative array with a key-value pair.
However, you can create a new array that contains the new key-value pair at the beginning of the array with the union operator +. The outcome is an entirely new array though and creating the new array has O(n) complexity.
The syntax is below.
$new_array = array('new_key' => 'value') + $original_array;
Note: Do not use array_merge(). array_merge() overwrites keys and does not preserve numeric keys.

In your situation, you want to use array_merge():
array_merge(array('fruit1'=>'cherry', 'fruit2'=>'blueberry'), array('fruit3'=>'apple', 'fruit4'=>'orange'));
To prepend a single value, for an associative array, instead of array_unshift(), again use array_merge():
array_merge(array($key => $value), $myarray);

Using the same method as #mvpetrovich, you can use the shorthand version of an array to shorten the syntax.
$_array = array_merge(["key1" => "key_value"], $_old_array);
References:
PHP: array_merge()
PHP: Arrays - Manual
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

#Cletus is spot on. Just to add, if the ordering of the elements in the input arrays are ambiguous, and you need the final array to be sorted, you might want to ksort:
$resulting_array = $array1 + $array2;
ksort($resulting_array);

If using Laravel, you can use prepend on a collection instance
collect(['b' => 'b', 'c' => 'c'])->prepend('a','a');
// ['a'=>'a', 'b' => 'b', 'c' => 'c']
https://laravel.com/docs/9.x/collections#method-prepend

Related

how to make array like this

I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}

Convert Array into Key Value Pair array

I have a comma separated string which i explode into an array. If the array is of un-known length and i want to make it into a key value pair array where each element in the array has the same key, how do i do this? i'm assuming i'd have to use array_combine? can anyone give me an example using the array bellow? :
for instance:
array([0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape)
into:
array([animal]=>zebra, [animal]=>cow, [animal]=>dog, [animal]=>monkey, [animal]=>ape)
You can't use the same key for each element in your array. You need a unique identifier to access the value of the array. When you use animal for all, what value should be used? What you can do is to make a 2 dimensional array that you have an array inside an array:
array(
[animals] => array(
[0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape
)
)
this can be used with $array['animals'][0]
But still you need numbers or unique identifiers to access the values of the array.
Something like this:
$string = 'zebra,cow,dog,monkey,ape';
$array = explode(',', $string);
$arrayReturn['animals'] = $array;
print_r($arrayReturn);
u cant have same key for all the values but u can do this
lets say your string is
$a = 'dog,ant,rabbit,lion';
$ar = explode(',',$a);
$yourArray = array();
foreach($ar as $animals){
$yourArray['animals']=$animals;
}
Now it doesnot matter how long your string is you will have you array as
$yourArray['animals'][0]='dog'
$yourArray['animals'][1]='ant'
....... so on ......

associative to numeric array in PHP

I have an associative array, which keys I want to use in numbers. What I mean: The array is kinda like this:
$countries = array
"AD" => array("AND", "Andorra"),
"BG" => array("BGR", "Bulgaria")
);
Obviously AD is 0 and BG is 1, but when I print $countries[1] it doesn't display even "Array".
When I print $countries[1][0] it also doesn't display anything. I have the number of the key, but I shouldn't use the associative key.
Perfect use case for array_values:
$countries = array_values($countries);
Then you can retrieve the values by their index:
$countries[0][0]; // "AND"
$countries[0][1]; // "Andorra"
$countries[1][0]; // "BGR"
$countries[1][1]; // "Bulgaria"
array_keys() will give you the array's keys. array_values() will give you the array's values. Both will be indexed numerically.
you might convert it into a numeric array:
$countries = array(
"AD" => array("AND", "Andorra"),
"BG" => array("BGR", "Bulgaria")
);
$con=array();
$i=0;
foreach($countries as $key => $value){
$con[$i]=$value;
$i++;
}
echo $con[1][1];
//the result is Bulgaria
There are a couple of workarounds to get what you want. Besides crafting a secondary key-map array, injecting references, or an ArrayAccess abomination that holds numeric and associative keys at the same time, you could also use this:
print current(array_slice( current(array_slice($countries, 1)), 0));
That's the fugly workaround to $countries[1][0]. Note that array keys appear to appear in the same order still; bemusing.

How to add an item to the beginning of an array?

In the script below, I need to add an item "None" with value of "" to the beginning of the array.
I'm using the $addFonts array below to do that, however, its being added to the select menu as "Array". What am I missing?
$googleFontsArray = array();
$googleFontsArrayContents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$googleFontsArrayContentsArr = unserialize($googleFontsArrayContents);
$addFonts = array(
'' => 'None'
);
array_push($googleFontsArray, $addFonts);
foreach($googleFontsArrayContentsArr as $font)
{
$googleFontsArray[$font['css-name']] = $font['font-name'];
}
Checkout array_unshift().
Should just be
$googleFontsArray['None'] = '';
This array is associative.
Add the first element in an array.
array_unshift()
$sampleArray = array("Cat", "Dog");
array_unshift($sampleArray ,"Horse");
print_r($sampleArray); // output array - array('horse', 'cat', 'dog')
Remove first element from an array.
array_shift()
Perhaps you want to use
array_merge($googleFontsArray, $addFonts);
?
If you just want to add one element to the beginning of an existing array, use array_unshift():
http://www.php.net/manual/en/function.array-unshift.php
Here is a complete list of array functions:
http://www.php.net/manual/en/ref.array.php
You can use the addition operator:
$a = array('Foo' => 42);
$a = array('None' => null) + $a;
Note that most people would consider it bad practice to let the position of a pair be significant, when using associative arrays. This is unique for php - other languages have either vectors (non-associative arrays) or hashmaps (Associative arrays).

Combining add and replacing values

Im curious to know if php has a function that allows me to connect 2 arrays together and replace values from array1 with values of array2 if the values from array2 already exist. see example
array1('value1','value2','value3',);
array2('value4','value2','value1');
array3 = functionEmerge(array1, array2);
array3('value1','value2','value3','value4',);
You could call array_unique() on the result of array_merge() to get your desired result.
I believe you are talking about taking the union of two arrays. If that's the case, PHP comes with the union array operator, which is just +. So:
$arr = array('value1', 'value2', 'value3') + array('value1', 'value2', 'value4');
Should get you:
array('value1', 'value2', 'value3', 'value4')
I could be wrong, so test this before you use it.
the function you're looking for is called array_merge
array array_merge ( array $array1 [, array $array2 [, array $... ]] )
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.
I didn't find a single operator for that, but this will work:
$array3 = array_keys(array_flip($array1) + array_flip($array2))
Set::merge( $a, $b )

Categories