How do I pass array keys to an array in PHP [duplicate] - php

This question already has answers here:
Create an assoc array with equal keys and values from a regular array
(3 answers)
Closed 6 years ago.
I have this array:
$a = array('b', 'c', 'd');
Is there a simple method to convert the array to the following?
$a = array('b' => 'b', 'c' => 'c', 'd' => 'd');

$final_array = array_combine($a, $a);
Reference: http://php.net/array-combine
P.S. Be careful with source array containing duplicated keys like the following:
$a = ['one','two','one'];
Note the duplicated one element.

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:
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.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}

Related

I get a different behavior after unset() elements [duplicate]

This question already has answers here:
json with no index after unset encode array in php
(6 answers)
Closed 8 months ago.
I get a strange behavior when I remove data from my array with unset
$array = [['name' => "pepe"], ['name' => 'marta']];
unset($array[0]);
unset($array[1]);
And I append more objects to the array
$array[] = $value1;
$array[] = $value2;
echo json_encode($array);
When I convert $array into an object I get this key values insted of index values
{"2":{"name":"mario"},"3":{"name":"hector"}}
Expected output
[{"name":"mario"},{"name":"hector"}]
That's because php unset doesn't reduce the length of the array, it just empty the given key.
Since it doesn't change the length, whe. You do $array[] = something you continue incrementing the index, creating the 2 and 3 index you are seeing.
When you do json_encode, since the keys doesn't start from zero (or aren't contiguous), it need to represent this array as an object.
Exemplifying:
$var1 = [1 => 'a', 3 => 'b'];
Can only be serialized to
{"1": "a", "3": "b"}
Because you can't define the index of an array item using JSON.
Solution
You can still use unset(), but you need to get only array values using the array_values() function:
$array = [['name' => "pepe"], ['name' => 'marta']];
unset($array[0]);
unset($array[1]);
$array[] = $value1;
$array[] = $value2;
// $array is now [2=>$value1, 3=>$value2]
$array = array_values($array);
// $array is now [$value1, $value2]
echo json_encode($array);
// Now the json outputs as expected by you: ["value1", "value2"]

Moving first value and key to the end on an array [duplicate]

This question already has answers here:
How do I move an array element with a known key to the end of an array in PHP?
(4 answers)
Closed 4 years ago.
I have an array that looks something like this:
'array_1' => [
'A' => 'A', 'B' => 'B', 'C' => 'C',
],
I need to shift the first value and key to the end of the array, so it should look like this:
'array_1' => [
'B' => 'B', 'C' => 'C', 'A' => 'A',
],
I've tried to do it like this:
array_push($arr, array_shift($arr));
But the result is this:
'array_1' => [
'B' => 'B', 'C' => 'C', '0' => 'A',
],
The key for value A changed to 0 but i need it ro remain A. Any suggestions?
array_push does not allow you to enter a key.
Therefore you have to use
$arr['key'] = value
First, do a reset(array). This reset the internal pointer to point at the first element
So that when you use key($arr), it will return the first key.
Then use array_shift() to get the first value in the array
Code:
reset($arr)
$arr[key($arr)] = array_shift($arr);
array_push($arr, array_shift($arr));
This removes the first VALUE of $arr, and then adds it to the end of the array as a value, therefore with a numeric key. Since there are no extant numeric keys, it is assigned key 0. Hence your result.
You need to extract the first pair, and push that:
reset($arr);
list($k, $v) = each($arr);
array_shift($arr);
$arr[$k] = $v;
That said... if you're relying on non-numeric key order (or mixed numeric/non-numeric keys), then I fear that your design might be flawed.
A keypair array (a dictionary, or sometimes hash or map) has no key order in most languages and even several representations (most notably, JSON - even if most JSON libraries usually maintain insertion order). Assuming it has might be setting oneself up for a fall.

is there a standard PHP function for transfering an associative array elements to another associative array

Is there a standard PHP function that changes an associative array's index names?
$a1 = array('one'=>1,'two'=>2,'three'=>3);
$new_index_names = array('one'=>'ono','two'=>'dos','three'=>'tres');
$a2 = change_index_names($a1,$new_index_names);
print_r($a2);
// $a2 should have the index names changed accordingly and look like this:
// array('ono'=>1,'dos'=>2,'tres'=>3)
EDIT
Please note that the function needs to know the mappings to the new index names. Meaning, in $new_index_names array provides the mappings. So again, it needs to know that 'ono' is the new index name for 'one'.
EDIT
I know you guys can come up with your own solution, i was wondering there is a standard PHP function that already does this.
EDIT
There are several situations where changing index names would help:
1) separates post value names to generic/internal names so you can separate
your backend code from front-end code.
2) say for instance you have two arrays from post that need to go through the
same exact process, except both arrays although mean/contain same exact type
of values/order/structure, they're index names are different. So when
passing to a function/method that goes by only a set of index names, you'll
need to convert the index names before passing them to that function/method.
You don't need array_values To get your desired output you can just use
array_combine($new_index_names,$a1);
not in just 1 function, but you could use array_values to get the values of the first array, and array_combine to set the new keys
Assuming both arrays has equal count, one way is with array_combine() and array_values()
$a2 = array_combine(array_values($new_index_names), $a1);
The previous answers does not consider the order of $a1 and $new_index_names, so I put my solution following:
$a1 = array('one' => 1, 'two' => 2, 'three' => 3, 'zero' => 0);
$new_index_names = array('zero' => 'zero', 'one' => 'ono', 'two' => 'dos', 'three' => 'tres');
array_combine(
$new_index_names,
str_replace(array_keys($a1), array_values($a1), array_keys($new_index_names))
);
Array
(
[zero] => 0
[ono] => 1
[dos] => 2
[tres] => 3
)
The best answer I've seen thus far:
foreach ($a1 as $k => $v) $a2[$new_index_names[$k]] = $v;
Credits go to jh1711

Modify value of a deep key in an associative array [duplicate]

This question already has answers here:
How to access and manipulate multi-dimensional array by key names / path?
(10 answers)
Closed 6 years ago.
Let's assume we have a simple $array like the following.
$array = array(
'a' => array(
'b' => array(
'c' => 'd'
),
'e' => 'f'
),
'g' => 'h'
);
Given an arbitrary array of $keys = array('a', 'b', 'c') and a value $value = 'i', I would like to change value of $array['a']['b']['c'] to i.
For simplicity, let's assume that elements of $keys are all valid, i.e. for any positive j, $keys[j] exists and is a child of $keys[j - 1].
I came up with a solution by passing a reference to the array and looping over keys but my implementation seems a bit ugly. Is there any straight forward way of doing this?
// current key index (starting at 0)
$i = 0;
// current array (starting with the outermost)
$t = &$array;
// continue until keys are exhausted
while ($i < count($keys) - 1) {
// update array pointer based on current key
$t = &$t[$keys[$i++]];
}
// update value at last key
$t[$keys[$i]] = $value;
http://sandbox.onlinephpfunctions.com/code/0598f00ab719c005a0560c18f91ab00154ba9453

Somewhat efficient way to append array 1 to array 2, while preserving the numeric keys of array 2, and adding keys n through n + x to array 1?

This is sort of two questions, but there may be one overall answer for the whole problem. I have an array that I need to append onto another array. Both arrays must have specific numeric keys. My problems are:
I need the numeric keys for the array that I am appending onto to be preserved.
array_splice() and array_merge() won't work to join the arrays because numeric keys in both arrays will be reset.
I need to make the keys of the newly added elements to be n through n + x, meaning if n is 100 and x is 25, the keys for the newly added elements should be 100 through 125.
Can anyone think of a somewhat efficient way of doing this?
EDIT
For anyone curious, found a better way of adding the correct keys to the array.
// add correct keys
$array_segment = array_combine(range($offset, $offset + count($array_segment) - 1), $array_segment);
// merge arrays while maintaining keys
$first_array = $first_array + $array_segment;
I think this is a very simple solution but, if I understand well what you want, it works and it's fast. In my opinion you can use this approach:
$array1 = array(1 => 'a', 2 => 'b', 3 => 'c');
$array2 = array(4 => 'd', 5 => 'e', 6 => 'f');
foreach($array2 as $key => $value)
$array1[$key] = $value;
var_dump($array1);
$array1[] = 'g';
$array1[] = 'h';
var_dump($array1);
You can see the result here:
http://codepad.org/ogD9drpK
Another way which will avoid the foreach is to execute this instruction:
// avoid the loop
//foreach($array2 as $key => $value)
// $array1[$key] = $value;
$array1 += $array2;
You can see the result here:
http://codepad.org/cZxCfRn6

Categories