Is there a native PHP function that can remove a set of keys from a array?
for eg. if I have a array like
array('a' => 'aaa', 'b' => 'bbb', 'c' => 'ccc', 'd' => 'ddd');
and I want to remove 'b', 'c' and get array('a' => 'aaa', 'd' => 'ddd'); ?
It's array_diff_key.
$input = array(...);
$remove = array_flip(array('a', 'b')); // 'a' and 'b' are the keys to remove
$output = array_diff_key($input, $remove);
See it in action.
$array = array('a', 'b', 'c', 'd')
foreach($array as $k=>$v){
if (in_array($v,array('b','c'))) unset($array[$k]);
}
An alternate to everyone else's answer, though all valid in their own way, is the array_splice function.
$foo = Array(
'a' => 'aaaa',
'b' => 'bbbb',
'c' => 'cccc',
'd' => 'dddd'
);
var_dump($foo);
array_splice($foo, 1, 2);
var_dump($foo);
Which produces:
array(4) {
["a"]=>
string(4) "aaaa"
["b"]=>
string(4) "bbbb"
["c"]=>
string(4) "cccc"
["d"]=>
string(4) "dddd"
}
array(2) {
["a"]=>
string(4) "aaaa"
["d"]=>
string(4) "dddd"
}
If you don't have too many fields to remove, you can use unset():
unset($foo['b']);
unset($foo['c']);
var_dump($foo)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I had a problem with my code. for example, I have an array like this :
[
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
]
I want to change my array to be like this:
[
['a' => 'f', 'b' => 'h', 'c' => 'j'],
['a' => 'g', 'b' => 'i', 'c' => 'k']
]
I need help to solve this. Thanks
I tested this on my local computer
<?php
$array = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$ultimate_array = array();
foreach($array as $key1 => $child_array)
{
foreach($child_array as $i => $key2)
{
if(empty($ultimate_array[$i])) $ultimate_array[$i] = array();
$ultimate_array[$i][$key1] = $key2;
}
}
print_r($ultimate_array);
?>
This is a simple demonstration:
<?php
$input = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$output = [];
foreach ($input as $key=>$entries) {
foreach ($entries as $entry) {
$output[$key][] = $entry;
}
}
var_dump($output);
Some would consider this variant more elegant:
<?php
$input = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$output = [];
array_walk($input, function($entries, $key) use (&$output) {
array_walk($entries, function($entry) use (&$output, $key) {
$output[$key][] = $entry;
});
});
var_dump($output);
The obvious output of both variants is:
array(3) {
["a"]=>
array(2) {
[0]=>
string(1) "f"
[1]=>
string(1) "g"
}
["b"]=>
array(2) {
[0]=>
string(1) "h"
[1]=>
string(1) "i"
}
["c"]=>
array(2) {
[0]=>
string(1) "j"
[1]=>
string(1) "k"
}
}
I want to make some encryption and write numbers
I used:
$a = [100,101,102,103,104,105]
function decrition (array $a){
return preg_replace('/101/','a',$a);
}
And it's returns me all letters "a" for each 101 in array.
How can I change next? 101 to "b", 102 to "c" etc.
return preg_replace('[101|102|103|104|105]','a',$a);
this method replace all this numbers to letter "a"
return preg_replace('[101|102|103|104|105','a|b|c|d|e',$a);
unfortunately it's not working
Why do you try to treat it as a string?
<?php
$a = [ 101, 102, 103 ];
$replace_array = array(101 => "a", 102 => "b");
$b = array_map(function($val) use ($replace_array) {
return (isset($replace_array[$val]) ? $replace_array[$val] : $val);
}, $a);
var_dump($a, $b);
Gives the following output:
array(3) {
[0]=>
int(101)
[1]=>
int(102)
[2]=>
int(103)
}
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
int(103)
}
Maybe you are looking for something like this?
$test = str_replace($a, array('a','b','c','d','e','f'), $a);
print_r($test);
This solution works
return str_replace(['101', '102', '103', '104', '105'], ['a', 'b', 'c', 'd', 'e'], $a);
I have an array with string indices, that I need partially sorted. That is, some elements must be moved first, but the others should remain untouched in their current (PHP-internal) order:
# The element with key "c" should be first
$foo = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
);
uksort($foo, function ($a, $b) {
if ($a === "c") {
return -1;
} elseif ($b === "c") {
return 1;
}
return 0;
});
var_dump($foo);
What I expected:
array(4) { ["c"]=> int(3) ["a"]=> int(1) ["b"]=> int(2) ["d"]=> int(4) }
//--------------------------^ "a" remains first of the unsorted ones
What I got:
array(4) { ["c"]=> int(3) ["d"]=> int(4) ["b"]=> int(2) ["a"]=> int(1) }
//--------------------------^ "d" moved above "a"
This seems due to the sorting algorithm uksort() uses internally, which destroys the fragile order of elements. Is there any other way to achieve this sorting?
Using any sort function is overkill for this task. You merely need to merge the input array into a lone array containing the element which should come first. The array union operator (+) will do nicely for your associative array (otherwise array_merge() will do).
Codes: (Demos)
if key c is guaranteed to exist:
$foo = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
);
$foo = ['c' => $foo['c']] + $foo;
var_export($foo);
if key c might not exist check for it first:
$bar = array(
"a" => 1,
"b" => 2,
"d" => 4,
);
if (array_key_exists('c', $bar)) {
$bar = ['c' => $bar['c']] + $bar;
}
var_export($bar);
Output:
array (
'c' => 3,
'a' => 1,
'b' => 2,
'd' => 4,
)
and
array (
'a' => 1,
'b' => 2,
'd' => 4,
)
This worked for me and returned:
array(4) { ["c"]=> int(3) ["a"]=> int(1) ["b"]=> int(2) ["d"]=> int(4) }
<?php
# The element with key "c" should be first
$foo = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
);
uksort($foo, function ($a, $b) {
if ($a === "c") {
return -1;
} else
return 1;
});
var_dump($foo);
?>
How can assign the values from one array to another array? For example:
//array with empty value
$targetArray = array(
'a' => '',
'b' => '',
'c' => '',
'd' => ''
);
// array with non-empty values, but might be missing keys from the target array
$sourceArray = array(
'a'=>'a',
'c'=>'c',
'd'=>'d'
);
The result I would like to see is the following:
$resultArray = array(
'a'=>'a',
'b'=>'',
'c'=>'c',
'd'=>'d'
);
I think the function you are looking for is array_merge.
$resultArray = array_merge($targetArray,$sourceArray);
Use array_merge:
$merged = array_merge($targetArray, $sourceArray);
// will result array('a'=>'a','b'=>'','c'=>'c','d'=>'d');
Use array_merge():
$targetArray = array('a'=>'','b'=>'','c'=>'','d'=>'');
$sourceArray = array('a'=>'a','c'=>'c','d'=>'d');
$result = array_merge( $targetArray, $sourceArray);
This outputs:
array(4) {
["a"]=>
string(1) "a"
["b"]=>
string(0) ""
["c"]=>
string(1) "c"
["d"]=>
string(1) "d"
}
Perhaps a more intuitive/indicative function for this task is array_replace(). It performs identically to array_merge() on associative arrays. (Demo)
var_export(
array_replace($targetArray, $sourceArray)
);
Output:
array (
'a' => 'a',
'b' => '',
'c' => 'c',
'd' => 'd',
)
A similar but not identical result can be achieved with the union operator, but notice that its input parameters are in reverse order and the output array has keys from $targetArray then keys from $sourceArray.
var_export($sourceArray + $targetArray);
Output:
array (
'a' => 'a',
'c' => 'c',
'd' => 'd',
'b' => '',
)
Given two arrays:
$foo = array('a', 'b', 'c');
$bar = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
Is there a built-in PHP function to produce the following result array?
$result = array('a' => 1, 'b' => 2, 'c' => 3);
I've been through the Array Functions list on php.net, but can't seem to find what I'm looking for. I know how to do it myself if need be, but I figured this might be a common-enough problem that there might be a built-in function that does it and didn't want to reinvent the wheel.
Another way using array_flip and array_intersect_keys:
$foo = array('a', 'b', 'c');
$bar = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$common = array_intersect_key($bar, array_flip($foo));
Output
array(3) {
["a"]=>
int(0)
["b"]=>
int(1)
["c"]=>
int(2)
}
It's a bit of a dirty hack, but it works:
function extractKeys($keys, $data) {
extract($data);
return call_user_func_array('compact', $keys);
}
$foo = array('a', 'b', 'c');
$bar = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
var_dump(extractKeys($foo, $bar));
Output:
array(3) {
["a"]=>
int(1)
["b"]=>
int(2)
["c"]=>
int(3)
}
After posting, I thought of one way of doing this:
array_intersect_key($bar, array_fill_keys($foo, NULL))
Though, this isn't really the concise, built-in function that I had hoped for, it's definitely better than constructing the resultant array manually.