Reputation: 17
I have several arrays from $ _REQUEST. For example: $ _REQUEST ['name'] and $ _REQUEST ['email']. That is, inside these arrays there is also an array. It turns out an array in an array.
Assigned them value
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
now I need to remove the first key with the value. For this I used array_shift
array_shift($name);
array_shift($email);
so i got rid of the first value. But, besides the name and email, there are others. It would not be desirable for everyone to write array_shift. How can I apply to all with one function?
thanx
UPD
For example $_REQUEST array:
Array (
[name] => Array (
[0] =>
[1] => myName
)
[email] => Array (
[0] =>
[1] => myEmail
)
[other] => Array (
[0] =>
[1] => otherDatas
)
)
I must get rid of these empty elements
Upvotes: 0
Views: 468
Reputation: 1048
If I understand correctly, you have multiple arrays in your request and you want to do an array_shift
on all of them?
You could loop through your $_REQUEST
and apply that function to all the arrays. Maybe like this:
foreach ($_REQUEST as &$value) {
if (is_array($value) && empty($value[0])) {
array_shift($value);
}
}
That will shift all arrays in your request and leave any other variables alone.
EDIT: Updated the example to only shift arrays where the first element is empty.
EDIT2: Added &
to $value
so that you can change the $_REQUEST
variable directly.
Upvotes: 1
Reputation: 163457
What you might do is create an array with the keys that you want from $_REQUEST
and use array_intersect_key to get your subset.
Then use array_map to check if the value is an array and return that value using array_filter to remove all values that you consider empty:
$keys = [
"name",
"email"
];
$result = array_map(function ($x) {
if (is_array($x)) {
return array_filter($x, function($y){
return null !== $y && "" !== trim($y);
});
}
return $x;
}, array_intersect_key($_REQUEST, array_flip($keys)));
print_r($result);
Upvotes: 0
Reputation: 7065
array_filter will clear empty values even if they are at any index.
$cleanArray = array();
foreach ($_REQUEST as $key => $value) {
$cleanArray[$key] = array_filter($value);
}
Output
Array (
[name] => Array (
[1] => myName
)
[email] => Array (
[1] => myEmail
)
[other] => Array (
[1] => otherDatas
)
)
Please note, it will also clear values like null
, (blank)
and false
. Example Reference
Upvotes: 0