I have an array that looks something like this:
Array
(
[0] => apple
["b"] => banana
[3] => cow
["wrench"] => duck
)
I want to take that array and use array_filter or something similar to remove elements with non-numeric keys and receive the follwoing array:
Array
(
[0] => apple
[3] => cow
)
I was thinking about this, and I could not think of a way to do this because array_filter does not provide my function with the key, and array_walk cannot modify array structure (talked about in the PHP manual).
Using a foreach loop would be appropriate in this case:
foreach ($arr as $key => $value) {
if (!is_int($key)) {
unset($arr[$key]);
}
}
It can be done without writing a loop in one (long) line:
$a = array_intersect_key($a, array_flip(array_filter(array_keys($a), 'is_numeric')));
What it does:
Since array_filter works with values, array_keys first creates a new array with the keys as values (ignoring the original values).
These are then filtered by the is_numeric function.
The result is then flipped back so the keys are keys once again.
Finally, array_intersect_key only takes the items from the original array having a key in the result of the above (the numeric keys).
Don't ask me about performance though.
As of PHP 5.6, it's now possible to use array_filter in a compact form:
array_filter($array, function ($k) { return is_numeric($k); }, ARRAY_FILTER_USE_KEY);
Demo.
This approach is about 20% slower than a for loop on my box (1.61s vs. 1.31s for 1M iterations).
As of PHP 7.4, it's possible to also use short closures::
array_filter($array, fn($k) => is_numeric($k), ARRAY_FILTER_USE_KEY);
Here's a loop:
foreach($arr as $key => $value) {
if($key !== 0 and !intval($key)) {
unset($arr[$key]);
}
}
Related
I'm getting started with PHP and I have some troubles finding a way to output values from multiples arrays sent from an external site.
I did a foreach and the code that is printed looks like this :
Array
(
[id] => 1
[title] => Title 1
)
Array
(
[id] => 2
[title] => Title 2
)
Array
(
[id] => 3
[title] => Title 3
)
Any idea how I could get every id (1,2,3) in an echo?
Let me know if you need more informations!
Thanks a lot!
If you just want to echo all the id's in all the arrays, a simple solution would be:
foreach ([$array1, $array2, $array3] as $arr) {
echo $arr['id'];
}
A better solution would probably to create one main array first:
$mainArray = [];
and every time you get a new array, you just push them to the main array:
$mainArray[] = $array1;
$mainArray[] = $array2;
// ... and so on
Then you'll have a multi dimensional array and can loop them with:
foreach ($mainArray as $arr) {
echo $arr['id'];
}
Which solution that works best depends on how you get the arrays and how many they are.
Note: Using array_merge() as others have suggested will not work in this case, since all the arrays have the same keys. From the documentation on array_merge(): "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one."
As you can do:
$array = array_merge_recursive($arr1, $arr2, $arr3);
var_dump($newArray['id']);
echo implode(",", $newArray['id']);
A demo code is here
$key = "cat"
$array = array( dog,
bird,
cat,
moon );
Need order like this (by key):
cat, dog, bird, moon.
$key = "cat" , so string "cat" need to be first element of array.
How to do that?
You're not actually sorting, just moving something in the array to the beginning. It might be simpler but here is one way:
array_unshift($array, current(array_splice($array, array_search($key, $array), 1)));
array_search() finds the index of the element that contains $key
array_splice() removes that element
array_unshift() prepends that element to the array
All the above solutions will work fine with the provided input array
$array = array('dog','bird', 'cat','moon');
However if the input array in an associative array, then above solutions will not work. See the changed input array below:
$array = array('frist' => 'foo', 'dog','bird', 'cat','moon', 'cat');
It will be handy to use the following function in case of performance. It does not have overhead of calling too many builtin PHP array functions. Moreover it will work both sequential and associative PHP arrays. See the code segment below:
Function definition
function moveToTop($array, $key){
foreach ($array as $index => $value) ($value != $key) ? $newArray[$index] = $value : '';
array_unshift($newArray, $key);
return $newArray;
}
Function call
moveToTop($array, $key)
Output
Array
(
[0] => cat
[frist] => foo
[1] => dog
[2] => bird
[3] => moon
)
I have a multidimensional array in this format
[0] => Array
(
[0] => Supplier
[1] => Supplier Ref
)
I basically need to offset every array with a new field at the beginning, so the outcome should be:
[0] => Array
(
[0] => New Field
[1] => Supplier
[2] => Supplier Ref
)
If I can run a loop through each array using for/foreach then that would be great but I'm struggling to find a good method of doing this. Any ideas?
Thanks
I can think of three straightforward ways
Use a simple foreach and array_unshift
foreach($arr as &$item) {
array_unshift($item, 'new field');
}
Use array_walk to apply array_unshift to each array item (will modify the existing array)
array_walk($array, function(&$item) { array_unshift($item, 'new field'); });
Use array_map and array_unshift (will return a new array – but the arrays inside the original array will be modified nevertheless)
array_map(function(&$item) {
array_unshift($item, 'new field'); return $item;
}, $array);
You can use array_unshift() to offset array within array php. It prepend one or more elements to the beginning of an array.
I am new to php and still learning the language,
let say I have two array
For Example
Array
(
[house_id] => 6
[name] => Lake Villa
[floor] => 5
[unit] => 25
)
Array
(
[house_id] => 6
[name] => Lake Villa
[floor] => 5
[unit] => 25
[parking_id] => 9
[resident_count] => 4
)
How do i get the keys of 1st array onto second, what i am saying is, i just need house_id, name, floor, unit from second array and discard rest of the information.
However, they key is not same and dynamic, which means the first array key whatever returned is also present on second but with additional information. The information above is just an example and the keys might varies but whatever key on first array contains on second array too.
I tried this, but isn't working:
foreach($arr1 as $k=>$v) {
foreach($arr2 as $j=>$w) {
if(isset($arr2[$k]))
$arr[$k] = $w;
}
}
You could use array_intersect_key, to merge the arrays.
$newArray = array_intersect_key($array2, $array1);
Use array_intersect_key().
array_intersect_key() returns an array containing all the entries of
array1 which have keys that are present in all the arguments.
Code
var_dump(array_intersect_key($array1, $array2));
foreach($arr2 as $key=>$val){
if(!array_key_exists($key,$arr1))
unset($arr2[$key]);
}
change condition from
if(isset($arr2[$k]))
to
if($arr1[$k] == $arr2[$j]) // it will work.
and isset is used for checking the variable is set or not.
Try this:
foreach($arr2 as $k=>$v) {
//Check if key is in first array
if(!isset($arr1[$k])) {
//Key not in first array, remove from second array.
unset($arr2[$k]);
}
}
try this
$result_array = array_intersect_key($arr2, $arr1);
I'm having trouble sorting an array according to another array. I've tried usort, uksort and uasort but I'm getting nowhere. Other questions on stackoverflow are not directly applicable here, as my array structure is different. I want to sort this multidimensional array:
$main = Array (
[Technology] => Array ()
[World] => Array ()
[Europe] => Array ()
)
By using this index-array:
$index = Array (
[0] => Europe
[1] => Technology
[2] => World
)
Basically, in this example I would want Europe to come first in the $main array, Technology second and World third, as this is their positioning in the $index array. How do I do that? (Please disregard little syntax errors in the arrays above)
$main_sort = array()
foreach ($index as $key => $value) {
if ($main [$value]) $main_sorted [$value] = $main [$value];
}
Simply loop through the $index array and map those values to a new array using the values from the $main array.
Given $index and $main,
uksort($main, function ($k, $k2) use ($index) {
return array_search($k, $index) - array_search($k2, $index);
});
Array will be sorted according to keys specified in $index. Behavior of not-matched keys is unspecified.
This solution works if you don't have any value in $index which is not a key in $main (as is the case in your example):
$sorted = array_merge(array_flip($index), $main);
If the values of $index are a superset of the keys of $main, a possible solution is:
$sorted = array_intersect_assoc(array_merge(array_flip($index), $main), $main);
Keep in mind that letting PHP functions work on arrays is much faster than doing so "explicitly"