Reverse array values while keeping keys - php

Here is an array I have:
$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
What I would like to do is reverse the values of the array while keeping the keys intact, in other words it should look like this:
$a = array('a' => 'a5', 'b' => 'a4', 'c' => 'a3', 'd' => 'a2', 'e' => 'a1');
How should I go about it?
P.S. I tried using array_reverse() but it didn't seem to work

Some step-by-step processing using native PHP functions (this can be compressed with less variables):
$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
$k = array_keys($a);
$v = array_values($a);
$rv = array_reverse($v);
$b = array_combine($k, $rv);
var_dump($b);
Result:
array(5) {
'a' =>
string(2) "a5"
'b' =>
string(2) "a4"
'c' =>
string(2) "a3"
'd' =>
string(2) "a2"
'e' =>
string(2) "a1"
}

It is possible by using array_combine, array_values, array_keys and array_values. May seem like an awful lot of functions for a simple task, and there may be easier ways though.
array_combine( array_keys( $a ), array_reverse( array_values( $a ) ) );

Here another way;
$keys = array_keys($a);
$vals = array_reverse(array_values($a));
foreach ($vals as $k => $v) $a[$keys[$k]] = $v;

I think this should work..
<?php
$old = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
$rev = array_reverse($old);
foreach ($old as $key => $value) {
$new[$key] = current($rev);
next($rev);
}
print_r($new);
?>

This'll do it (just wrote it, demo here):
<?php
function value_reverse($array)
{
$keys = array_keys($array);
$reversed_values = array_reverse(array_values($array), true);
return array_combine($keys, $reversed_values);
}
$a = array('a' => 'a1', 'b' => 'a2', 'c' => 'a3', 'd' => 'a4', 'e' => 'a5');
print_r( value_reverse($a) );

Related

How do I combine two values from the same associative array?

I have an array that I need to get a value from within the same array that is unassigned to a variable:
return ['a' => 1, 'b'=> 'a', 'c' => 2];
So in this case I need 'b' to return the same value as 'a'. Which would be 1
Thanks for the help.
edit
I intend on running a function on b's value so the value of b is slightly different than a
return ['a' => 1, 'b'=> myFunction('a'), 'c' => 2];
You can try this way.
foreach ($array as $key => $agent) {
$array[$key]['agent_address_1'] = $agent['agent_company_1'] . ', ' .$agent['agent_address_1'];
unset($array[$key]['agent_company_1']);
}
What you want is not clear.
But i am assuming that you are trying to get the 'b' element of an array to be assigned a value similar to the value of 'a' element of that same array
If that is what you need, this will do it.
<?php
$a = array('a' => 1, 'b' => null, 'c' => 2);
$a['b'] = myFunction($a, 'a');
function myFunction($a, $b)
{
return $a[$b];
}
var_dump($a);
You can then return the array, or do what you want with it.
Maybe something like
<?php
function resolve(array $arr) {
foreach($arr as &$v) {
if ( isset($arr[$v])) {
$v = $arr[$v];
}
}
return $arr;
}
function foo() {
return resolve( ['a' => '5', 'b'=>'a', 'c' => '1'] );
}
var_export( foo() );
will do, prints
array (
'a' => '5',
'b' => '5',
'c' => '1',
)
But keep in mind that resolve( ['b'=>'a', 'a' => 'c', 'c' => '1'] ); will return
array (
'b' => 'c',
'a' => '1',
'c' => '1',
)
(you could resolve that with while( isset($arr[$v])) { instead of if ( isset($arr[$v]) ) { ...but there are most likely more elegant/performant ways to do that)

PHP Merge (Add) Two Arrays by Same Key

I have two arrays.
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
I want to merge these two arrays and get following result.
$c = array('a' => 5, 'b' => 12, 'c' => 18);
What is the easiest way to archive this?
Thanks!
As mentioned in the comments, looping through the array will do the trick.
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
$c = array();
foreach($a as $index => $item) {
if(isset($b[$index])) {
$new_value = $a[$index] + $b[$index];
$c[$index] = $new_value;
}
}
$c = array();
foreach ($a as $k => $v) {
if (isset($b[$k])) {
$c[$k] = $b[$k] + $v;
}
}
You need to check whether keys exist in both arrays.
You can simply use foreach as
foreach($b as $key => $value){
if(in_array($key,array_keys($a)))
$result[$key] = $a[$key]+$value;
}
You can easily do this by foreach loop, please see the example below
$c = array();
$a = array('a' => 2, 'b' => 5, 'c' => 8);
$b = array('a' => 3, 'b' => 7, 'c' => 10);
foreach ($a as $key => $value) {
$tmp_value = $a[$key] + $b[$key];
$c[$key] = $tmp_value;
}
print_r($c);

php string to associative array with value=>value pair

I have string
$string1 = `a,b,c,d`;
$array1 = explode(',', $string1);
Gives me :
array(
(int) 0 => 'a',
(int) 1 => 'b',
(int) 2 => 'c'
(int) 3 => 'd'
)
But I want it to be like this
array(
'a' => 'a',
'b' => 'b',
'c' => 'c'
'd' => 'd'
)
How do I do that
Use array_combine function
$string = `a,b,c,d`;
$array = explode(',', $string);
var_dump(array_combine($array, $array));
I think you have to create a new array after exploding...
$tmp_arr = explode(',', $string1);
$array1 = array();
foreach ($tmp_arr as $item){
$array1[$item] = $item;
}

php custom array_replace_recursive method

I need a custom array_replace_recursive($array, $array1) method which does what the original array_replace_recursive($array, $array1) method does except that for indexed array it should use the array in the second array and overwrite the first array recursively.
example:
$a = array (
'a' => array(1,2,3),
'b' => array('a' => 1, 'b' => 2, 'c' => 3)
);
$b = array (
'a' => array(4),
'b' => array('d' => 1, 'e' => 2, 'f' => 3)
);
$c = array_replace_recursive($a, $b);
current behaviour:
$c = array (
'a' => array(4,2,3),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 1, 'e' => 2, 'f' => 3)
);
desired behaviour:
$c = array (
'a' => array(4),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 1, 'e' => 2, 'f' => 3)
);
as you can see element 'a' is an indexed array so the element in the second array has overwritten the element in the first array. element 'b' is an associative array so it maintains the original behaviour.
Below worked for me:
<?php
/**
* This method finds all the index arrays in array2 and replaces array in array1. it checks for indexed arrays recursively only within associative arrays.
* #param $array1
* #param $array2
*/
function customMerge(&$array1, &$array2) {
foreach ($array2 as $key => $val) {
if(is_array($val)) {
if(!isAssoc($val)) {
if($array1[$key] != $val) {
$array1[$key] = $val;
}
} else {
$array1_ = &$array1[$key];
$array2_ = &$array2[$key];
customMerge($array1_, $array2_);
}
}
}
}
function isAssoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
$a = array (
'a' => array(1,2,3),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'g' => array(
4,5,6
))
);
$b = array (
'a' => array(4),
'b' => array('d' => 1, 'e' => 2, 'f' => 3, 'g' => array(
7
))
);
$c = array_replace_recursive($a, $b); // first apply the original method
$expected = array (
'a' => array(4),
'b' => array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 1, 'e' => 2, 'f' => 3, 'g'=> array(
7
)),
);
$d = $c; // create copy
customMerge($d, $b); // do the custom merge
echo $d == $expected;
The isAssoc() method in the first answer of this post is what your looking for:
How to check if PHP array is associative or sequential?
That method will check if the array is index and return true if it's the case.

How can I group same values in a multidimention array?

How can I group same values in a multidimention array?
I want this
array(
array('a' => 1, 'b' => 'hello'),
array('a' => 1, 'b' => 'world'),
array('a' => 2, 'b' => 'you')
)
to become
array(
array(
array('a' => 1, 'b' => 'hello'),
array('a' => 1, 'b' => 'world')
),
array('a' => 2, 'b' => 'you')
)
function array_gather(array $orig, $equality) {
$result = array();
foreach ($orig as $elem) {
foreach ($result as &$relem) {
if ($equality($elem, reset($relem))) {
$relem[] = $elem;
continue 2;
}
}
$result[] = array($elem);
}
return $result;
}
then
array_gather($arr,
function ($a, $b) { return $a['a'] == $b['a']; }
);
This could be implemented in a more efficient matter if all your groups could be reduced to a string value (in this case they can, but if your inner arrays were something like array('a' => ArbitraryObject) they could not be).

Categories