Am I overlooking a function in PHP that will merge arrays without preserving keys? I've tried both ways of these ways: $arrayA + $arrayB and array_merge($arrayA, $arrayB) but neither are working as I expected.
What I expect is that when I add array(11, 12, 13) and array(1, 2, 3) together that I would end up with array(11, 12, 13, 1, 2, 3).
I created a function of my own which handles it properly, though I was trying to figure out if it was the best way of doing things or if there's an easier or even a build in way that I'm just not seeing:
function array_join($arrayA, $arrayB) {
foreach($arrayB as $B) $arrayA[] = $B;
return $arrayA;
}
Edit:
array_merge() was working as intended, however I had the function running in a loop and I was using the incorrect variable name inside the function, so it was only returning a partial list as is what I was experiencing. For example the loop I was using ended on array(13, 1, 2, 3).
Have you actually tested your code? because array_merge should be enough:
From the documentation of array_merge:
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. (emphasis are mine)
<?php
$a1 = array(11, 12, 13);
$a2 = array(1, 2, 3);
$x = array_merge($a1, $a2);
print_r($x);
It print this on my console:
Array
(
[0] => 11
[1] => 12
[2] => 13
[3] => 1
[4] => 2
[5] => 3
)
$arr1 = array(11, 12, 13);
$arr2 = array(1, 2, 3);
print_r(array_merge($arr1,$arr2));
Try this :
function array_join($arrayA, $arrayB) {
foreach($arrayB as $B) $arrayA[count($arrayA)] = $B;
return $arrayA;
}
Related
I have an array (as shown below). It has a and b, the numbers inside of each of them. However, when I use the end() function, it gives me b's array. I want the actual b letter. to be printed, not the number array. How can I do this?
<?php
$array = array("a" => array(1, 2, 3),
"b" => array(4, 5, 6));
$end = end($array);
print_r($end); // gives me 4, 5, 6. I want the value b
Use end with array_keys instead:
$array = array("a" => array(1, 2, 3),
"b" => array(4, 5, 6));
$keys = array_keys($array);
$end = end($keys);
print_r($end);
Note that since end adjusts the array pointer (hence you can't pass the output from array_keys directly to end without a notice level error), it's probably preferable to simply use
echo $keys[count($keys)-1];
Simply
$array = array("a" => array(1, 2, 3),"b" => array(4, 5, 6));
end($array);
echo key($array);
Output
b
Sandbox
the call to end puts the internal array pointer at the end of the array, then key gets the key of the current position (which is now the last item in the array).
To reset the array pointer just use:
reset($array); //moves pointer to the start
You cant do it in one line, because end returns the array element at the end and key needs the array as it's argument. It's a bit "Weird" because end moves the internal array pointer, which you don't really see.
Update
One way I just thought of that is one line, is to use array reverse and key:
echo key(array_reverse($array));
Basically when you do array_reverse it flips the order around and returns the reversed array. We can then use this array as the argument for key(), which gets the (current) first key of our now backwards array, or the last key of the original array(sort of a double negative).
Output
b
Sandbox
Enjoy!
A simple way to do it would be to loop through the keys of the array and store the key at each index.
<?php
$array = array("a" => array(1, 2, 3),
"b" => array(4, 5, 6));
foreach ($array as $key => $value) $end = $key;
// This will overwrite the value until you get to the last index then print it out
print_r($end);
I need to sort the following flat, associative array by its keys, but not naturally. I need to sort the keys by a predefined array of values.
$aShips = [
'0_204' => 1,
'0_205' => 2,
'0_206' => 3,
'0_207' => 4
];
My order array looks like this:
$order = ["0_206", "0_205", "0_204", "0_207"];
The desired result:
[
'0_206' => 3,
'0_205' => 2,
'0_204' => 1,
'0_207' => 4
]
I know how to write a custom sorting function, but I don't know how to integrate the order array.
function cmp($a, $b){
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
uasort($aShips, "cmp");
If you want to sort by keys. Use uksort. Try the code below.
<?php
$aShips = array('0_204' => 1, '0_205' => 2, '0_206' => 3, '0_207' => 4);
uksort($aShips, function($a, $b) {
return $b > $a;
});
According to the Official PHP Docs, you can use uasort() like this (just for demo):
<?php
// Comparison function
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);
// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);
?>
You don't need to leverage a sorting algorithm.
Simply flip $order to use its values as keys (maintaining their order), then merge the two arrays to replace the unwanted values of $order with the values from $aShip.
This assumes that $aShip includes all key values represented in $order, of course. If not, array_intersect_key() can be used to filter $order, but this is dwelling on a fringe case not included in the posted question.
Code: (Demo)
var_export(array_replace(array_flip($order), $aShips));
Output:
array (
'0_206' => 3,
'0_205' => 2,
'0_204' => 1,
'0_207' => 4,
)
This also works when you haven't listed every occurring key in $order -- the unlisted keys are "moved to the back". Proven by this Demo.
Using a custom sorting algorithm can be done and there will be a number of ways, but I'll only show one for comparison's sake.
Reverse your order array and use it as a lookup array while asking uksort() to sort in a descending fashion. If an encountered key is not found in the lookup assign it a value of -1 to ensure it moves to the back of the array.
Code: (Demo)
$lookup = array_flip(array_reverse($order));
uksort($aShips, function($a, $b) use ($lookup) {
return ($lookup[$b] ?? -1) <=> ($lookup[$a] ?? -1);
});
var_export($aShips);
If you don't like reversing the lookup and sorting DESC, you can count the order array to determine a fallback value. This alternative script uses arrow function syntax for brevity and to gain direct access to the variables declared outside of the closure. (Demo)
$lookup = array_flip($order);
$default = count($order);
uksort($aShips, fn($a, $b) => ($lookup[$a] ?? $default) <=> ($lookup[$b] ?? $default));
var_export($aShips);
To shuffle an array in php is easy but my problem is when i try to shuffle it without getting the same result before of after that key.
Example:
Array ( 0 => 1, 1 => 2, 2 => 3, 3 => 3 )
I must have a result without 3 coming together.
Example of some array i want:
Array ( 0 => 2, 1 => 3, 2 => 1, 3 => 3 )
I've tryed to check each item of the array, if that happens i shuffle it again, and check another time. But that seems to be waste both on time and process.
EDIT:
Here is the code i use:
do
{
$not_valid=false;
for($i=0;$i<sizeof($arr_times)-1;$i++){
if($arr_times[$i]==$arr_times[$i+1])
$not_valid=true;
}
if($not_valid)
shuffle($arr_times);
}while ($not_valid);
Even though php has really a lot of strange functions - it doesn't have any for described situation.
So you have to do that manually.
PS: also it would be a good idea to check if it's even possible to shuffle input array in an expected way so you wouldn't get into an infinite loop.
From Shuffle list, ensuring that no item remains in same position
<?php
$foo = array(
0,
1,
2,
3,
4,
);
for ($i = 0, $c = sizeof($foo); $i < $c - 1; $i++) {
$new_i = rand($i + 1, $c - 1);
list($foo[$i], $foo[$new_i]) = array($foo[$new_i], $foo[$i]);
}
var_export($foo); // Derangement
I need to count the number of times a value occurs in a given array.
For example:
$array = array(5, 5, 2, 1);
// 5 = 2 times
// 2 = 1 time
// 1 = 1 time
Does such a function exist? If so, please point me to it in the php docs... because I can't seem to find it.
Thanks.
Yes, it's called array_count_values().
$array = array(5, 5, 2, 1);
$counts = array_count_values($array); // Array(5 => 2, 2 => 1, 1 => 1)
array_count_values
I have an 'dictionary' array such as this:
$arr['a']=5;
$arr['b']=9;
$arr['as']=56;
$arr['gbsdfg']=89;
And I need a method that, given a list of the array keys, I can retrieve the corresponding array values. In other words, I am looking for a built-in function for the following methods:
function GetArrayValues($arrDictionary, $arrKeys)
{
$arrValues=array();
foreach($arrKeys as $key=>$value)
{
$arrValues[]=$arrDictionary[$key]
}
return $arrValues;
}
I am so sick of writing this kind of tedious transformation that I have to find a built-in method to do this. Any ideas?
array_intersect_key
If you have an array of keys as values you can use array_intersect_key combined with array_flip. For example:
$values = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$keys = ['a', 'c'];
array_intersect_key($values, array_flip($keys));
// ['a' => 1, 'c' => 3]