I have this function, where a array_filter function is included:
$var = "test";
function mainFunction() {
global $var;
$myNewArray = array();
$data = array("a", "b", "c");
array_filter($data, function ($value) {
global $myNewArray;
$myNewArray[] = $value;
});
print_r($myNewArray); // TEST OUTPUT
}
mainFunction();
Problem:
My test output myNewArray is empty.
I know that my array_filter function is senless at the moment until I check no values.
But only for testing, I would like to use it, to create a newArray. But this doesn’t work. Where is my mistake?
UPDATE
I updated my code:
function mainFunction() {
global $var;
$myNewArray = array();
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");
$myNewArray = array_filter($data, function ($value) {
if ($value['content'] == "World") {
return $value['content'];
}
});
print_r($myNewArray); // TEST OUTPUT
}
mainFunction();
This works, but not correctly.
I would like to save only the content value.
But my $myNewArray looks like this:
Array
(
[0] => Array
(
[id] => 2
[content] => World
)
)
Instead of
Array
(
[0] => Array
(
[content] => World
)
)
5
Answers
In mainFunction you are not using
$myNewArray
as global so it’s only in the scope, but in the array_filter function you are usingglobal $myNewArray;
Here is an example of you code without global
$myNewArray
Answer to Update:
You can use array_reduce to achieve that
Everything seems to work fine.
The output is just like expected:
But if you want to leave only some fields in resulting array, array_filter will not help you (at least without a crutch).
You may want to iterate source array and filter it by yourself.
The output then would be:
you can use this code……….
I would combine
array_filter
andarray_map
for this.Example: https://phpize.online/s/9U
You want two different things :
Filter your array
On your second attempt you’ve done it right but
array_filter
callback function expect aboolean
as the return value. It will determine whereverarray_filter
need to keep the value or not.Map your array
You need to remove all value on each element except the
"content"
value. You can usearray_map
to do that.