Get values of array using as key values of another array - php

I have an array with some values (numeric values):
$arr1 = [1, 3, 8, 12, 23]
and I have another associative array that a key (which matches to a value of $arr1) correspond to a value. This array may contain also keys that don't match with $arr1.
$arr2 = [1 => "foo", 2 => "foo98", 3 => "foo20", 8 => "foo02", 12 => "foo39", 15 => "foo44", 23 => "foo91", 34 => "foo77"]
I want as return the values of $arr2 specifying as key the values of $arr1:
["foo", "foo20", "foo02", "foo39", "foo91"]
If possible, all this, without loops, using just PHP array native functions (so in an elegant way), or at least with the minimum number of loops possible.

Minimal loop is simple - 1. as:
foreach($arr1 as $k) {
$res[] = $arr2[$k];
}
You can do that with array_walk but I think this simple way is more readable.
If you insist you can do with array_filter + array_values + in_array as:
$res = array_values(array_filter($arr2,
function ($key) use ($arr1) { return in_array($key, $arr1);},
ARRAY_FILTER_USE_KEY
));
You can see this for more about filtering keys

To do it purely with array functions, you could do it as...
print_r(array_intersect_key($arr2, array_flip($arr1) ));
So array_flip() turns the items you want form the array into the keys for $arr1 and then uses array_intersect_key() to match the keys with the main array and this newly created array.
Gives...
Array
(
[1] => foo
[3] => foo20
[8] => foo02
[12] => foo39
[23] => foo91
)
If you don't want the keys - add array_values() around the rest of the calls...
print_r(array_values(array_intersect_key($arr2, array_flip($arr1) )));
to get
Array
(
[0] => foo
[1] => foo20
[2] => foo02
[3] => foo39
[4] => foo91
)
Although as pointed out - sometimes a simple foreach() is just as good and sometimes better.

Related

PHP - unset array where Key is X and Value is Y

I have this type of array,
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
[1] => Array --> I want to remove this value using its index, which is "1"
(
[id] => 2
[fams] => 5
)
)
I want to remove that array [1] entirely, using its index, so the condition is - where the ID is match, for example - [id] => 2
Is that possible, to remove a particular value with that specific condition?
and without looping (or any similar method that need to loop the array)
thanks in advance!
FYI - I did try to search around, but, to be honest, I'm not sure what "keyword" do I need to use.
I did try before, but I found, array_search, array_keys - and it seems those 2 are not.
I'm okay, if we need several steps, as long as it did not use "loop" method.
---update
I forgot to mention, that I'm using old PHP 5.3.
array_filter should work fine with PHP 5.3.
The downside of this approach is that array_filter will (internally) iterate over all your array's entries, even after finding the right one (it's not a "short-circuit" approach). But at least, it's quick to write and shouldn't make much of a difference unless you're dealing with very big arrays.
Note: you should definitely upgrade your PHP version anyway!
$array = array (
0 =>
array (
'id' => 0,
'fams' => 5
),
1 =>
array (
'id' => 2,
'fams' => 5
)
);
$indexToRemove = 2;
$resultArray = array_filter($array, function ($entry) use ($indexToRemove) {
return $entry['id'] !== $indexToRemove;
});
Demo: https://3v4l.org/6DXjl
You can use array_search to find the key of a sub-array that has a matching id value (extracted using array_column), and if found, unset that element:
if (($k = array_search(2, array_column($array, 'id'))) !== false) {
unset($array[$k]);
}
print_r($array);
Output:
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
)
Demo on 3v4l.org
It should be noted that although there is no explicit loop in this code, array_search and array_column both loop through the array internally.
You can use array_column to make id as index of the sub-array then use unset
$a = array_column($a, null, 'id');//new array id as index
$index = 2;// id to remove
if($a[$index]) unset($a[$index]);
print_r($a);
Working example :- https://3v4l.org/ofMr7

How to extract the keys of an Array and push them to a String array?

Everyone else usually asking how to convert string array with commas to an array of key value pairs.
But my question is opposite. I want to extract the keys of the array and place them in a separate array using PHP
I have an array of this form:
Array
(
[Lights] => 4
[Tool Kit] => 4
[Steering Wheel] => 4
[Side Mirrors] => 3.5
)
and I want output to be in this form:
{"Lights", "Tool Kit", "Steering Wheel", "Side Mirrors" }
Using array_keys :
array_keys — Return all the keys or a subset of the keys of an array
So you can just extract each keys simply by using this method
$keys = array_keys($array);
Otherwise, you can loop through each values and only get the keys :
$keyArray=array_keys($array);
$keyArray=[];
foreach($array as $key => $value){
$keyArray[]=$key;
}
Use array_keys. It will return array keys as array values
$array=array('Lights' => 4,
'Tool Kit' => 4,
'Steering Wheel' => 4,
'Side Mirrors' => 3.5);
$key_array=array_keys($array);
print_r($key_array);
It will result
Array ( [0] => Lights [1] => Tool Kit [2] => Steering Wheel [3] => Side Mirrors )
Looks like you are expecting JSON output. You can just use json_encode function in a pair with array_keys.
$result = json_encode(array_keys($array));
However, your result will be ["Lights","Tool Kit","Steering Wheel","Side Mirrors"]

sorting array based on child array[0] (unix) value

I need an array sorted by Unix timestamp values. I attempted to use both ksort and krsort before realising that occasionally the timestamp values might be the same (and you cannot have duplicate keys in arrays).
Here's an example array I may be faced with:
$array = array(
[
"unix" => 1556547761, // notice the two duplicate unix values
"random" => 4
],
[
"unix" => 1556547761,
"random" => 2
],
[
"unix" => 1556547769,
"random" => 5
],
[
"unix" => 1556547765, // this should be in the 3rd position
"random" => 9
]
);
So what I'm trying to do is sort them all based on each child arrays unix value, however I cannot figure out how to do so. I have tried countless insane ways (including all other sort functions and many, many for loops) to figure it out - but to no avail.
All help is appreciated.
You can use usort which sort your array by given function
Define function as:
function cmpByUnix($a, $b) {
return $a["unix"] - $b["unix"];
}
And use with: usort($array, "cmpByUnix");
Live example: 3v4l
Notice you can also use asort($array); but this will compare also the "random" field and keep the key - if this what you need then look at Mangesh answer
array_multisort() — Sort multiple or multi-dimensional arrays
array_columns() — Return the values from a single column in the input array
You can use array_multisort() and array_column(), then provide your desired sort order (SORT_ASC or SORT_DESC).
array_multisort(array_column($array, "unix"), SORT_ASC, $array);
Explanation:
In array_multisort(), arrays are sorted by the first array given. You can see we are using array_column($array, "unix"), which means that the second parameter is the order of sorting (ascending or descending) and the third parameter is the original array.
This is the result of array_column($array, "unix"):
Array(
[0] => 1556547761
[1] => 1556547761
[2] => 1556547765
[3] => 1556547769
)
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Note:If two members compare as equal, their relative order in the sorted array is undefined.
Refer : https://www.php.net/manual/en/function.asort.php
asort($array);
echo "<pre>";
print_r($array);
echo "</pre>";
It will give you the output as
Array
(
[1] => Array
(
[unix] => 1556547761
[random] => 2
)
[0] => Array
(
[unix] => 1556547761
[random] => 4
)
[3] => Array
(
[unix] => 1556547765
[random] => 9
)
[2] => Array
(
[unix] => 1556547769
[random] => 5
)
)
You can keep the array key [1],[0],[3],[2]) as it is Or you can keep it as sequential as per your requirement.

How to keep the previous values in array after new assignment?

I have an array named $arr = array. Some of its keys has value, like this:
$arr['1'] = 'one';
$arr['2'] = 'two';
$arr['3'] = 'three';
Now I initialize that array with another arry, some thing like this:
$arr = array('4' => 'four', '5' => 'five');
But I need to keep the previous values. I mean is, when I print that array, the output will be like this:
echo '<pre>';
print_r($arr);
/* ---- output:
Array
(
[4] => four
[5] => five
)
*/
While I want this output:
Array
(
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
)
So, How can I take care of old keys (values) after re-initialized?
Here are your options detailed below: array_merge, union (+ operator), array_push, just set the keys directly and make a function that just loops over the array with your own custom rules.
Sample data:
$test1 = array('1'=>'one', '2'=>'two', '3'=>'three', 'stringkey'=>'string');
$test2 = array('3'=>'new three', '4'=>'four', '5'=>'five', 'stringkey'=>'new string');
array_merge (as seen in other answers) will re-index numeric keys (even numeric strings) back to zero and append new numeric indexes to the end. Non numeric string indexes will overwrite the value where the index exists in the former array with the value of the latter array.
$combined = array_merge($test1, $test2);
Result (http://codepad.viper-7.com/c9QiPe):
Array
(
[0] => one
[1] => two
[2] => three
[stringkey] => new string
[3] => new three
[4] => four
[5] => five
)
A union will combine the arrays but both string and numeric keys will be handled the same. New indexes will be added and existing indexes will NOT be overwritten.
$combined = $test1 + $test2;
Result (http://codepad.viper-7.com/8z5g26):
Array
(
[1] => one
[2] => two
[3] => three
[stringkey] => string
[4] => four
[5] => five
)
array_push allows you to append keys to an array. So as long as the new keys are numeric and in sequential order, you can push on to the end of the array. Note though, non-numeric string keys in the latter array will be re-indexed to the highest numeric index in the existing array +1. If there are no numeric keys, this would be zero. You would also need to reference each new value as a separate argument (see arguments two and three below). Also, since the first argument is taken in by reference, it will modify the original array. The other options allow you to combine to a separate array in case you need the original.
array_push($test1, 'four', 'five');
Result (http://codepad.viper-7.com/5b9nvC):
Array
(
[1] => one
[2] => two
[3] => three
[stringkey] => string
[4] => four
[5] => five
)
You could also just set the keys directly.
$test1['4'] = 'four';
$test1['5'] = 'five';
Or even just make a loop and wrap it in a function to handle your custom rules for merging
function custom_array_merge($arr1, $arr2){
//loop over array 2
foreach($arr2 as $k=>$v){
//if key exists in array 1
if(array_key_exists($arr1, $k)){
//do something special for when key exists
} else {
//do something special for when key doesn't exists
$arr1[$k] = $v;
}
}
return $arr1;
}
The function could be expanded to use stuff like func_get_args to allow any number of arguments.
I'm sure there are also more "hacky" ways to do it using stuff like array_
splice or other array functions. However, IMO, I would avoid them just to keep the code a little more clear about what you are doing.
use array_merge:
$arr = array_merge($arr, array('4' => 'four', '5' => 'five'));
Well, as per the comments (which are correct) this will reindex the array, another solution to avoid that would be to do as follows:
array_push($arr, "four", "five");
But this would not work if you have different keys, like strings that are not masked numbers.
Another way is to use + in order to merge them maintaining keys:
$arr['1'] = 'one';
$arr['2'] = 'two';
$arr['3'] = 'three';
$arr2 = array('4' => 'four', '5' => 'five');
$arr = $arr + $arr2;
Another way to do it, and keeps the keys of the array, is using array_replace.
$arr['1'] = 'one';
$arr['2'] = 'two';
$arr['3'] = 'three';
print_r(array_replace($arr, array('4' => 'four', '5' => 'five')));
Output:
Array
(
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
)

Remove Values from PHP Array if Present

I have the following PHP array:
Array
(
[0] => 750
[1] => 563
[2] => 605
[3] => 598
[4] => 593
)
I need to perform the following action on the array using PHP:
Search the array for a value (the value will be in a
variable; let's call it $number). If the value
is present in the array, remove it.
If someone could walk me through how to do that, it would be much appreciated.
Note: If it makes it any easier, I can form the array so the keys are the same as the values.
$array = array_unique($array) // removes dupicate values
while(false !== ($num = array_search($num, $array))){
unset($array[$num]);
}
$max = max($array);
will search for all keys with value $num and unset them
lets say your $array
$array = array_unique($array) // removes dupicate values
$array = arsort($array)
$variable = $array[0] // the maximum value in the array, and place it in a variable.
$key = array_search($array, $number);
if($key){
unset($array[$key]) // Search array for a value, value is present in array, remove it.
}
array_search() and unset() seems a good method for your sample data in your question. I'll just show a different way for comparison's sake (or in case your use case is slightly different from what you have posted here).
Methods: (Demo)
$array=[750,563,605,598,593];
// if removing just one number apply the number as an array element
$number=605;
var_export(array_diff($array,[$number]));
// if you are performing this task with more than one $number, make $numbers=array() and do the same...
$numbers=[605,563]; // order doesn't matter
var_export(array_diff($array,$numbers));
// if you need to re-index the output array, use array_values()...
$numbers=[605,563]; // order doesn't matter
var_export(array_values(array_diff($array,$numbers)));
Output:
array (
0 => 750,
1 => 563,
3 => 598,
4 => 593,
)
array (
0 => 750,
3 => 598,
4 => 593,
)
array (
0 => 750,
1 => 598,
2 => 593,
)

Categories