-1

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
        )
)
Trombone0904
  • 4,132
  • 8
  • 51
  • 104
  • just do `$newArray = array_filter($oldArray, function($value) { return $something; });` as it returns a filtered array, you don't need to use global – Sudhir Bastakoti Dec 09 '22 at 07:44
  • 1
    What is the point of array_filter here? It is used to filter values from the array and not loop over the array. – nice_dev Dec 09 '22 at 07:52
  • `array_filter(php)` works with returning `true` or `false`. Always check the manual for parameter and return values when in doubt. https://php.net/array_filter - it can save you a lot of questions (and the manual also has usage examples very often). – hakre Dec 09 '22 at 08:16
  • _"I would like to use it, to create a newArray. But this doesn't work. Where is my mistake?"_ - with all due respect as you asked for it: `array_filter` is for _filtering_ an array, _**not** to create_ it. You may want to _reduce_ the array `$data`, so `array_reduce(php)` _might_ be a better fit. Compare https://php.net/array_reduce . -- and when using anonymous functions, check the `use` clause to "import" variables from the outer scope (also called _closure_ sometimes). – hakre Dec 09 '22 at 08:19
  • Related: [PHP array_column with array_filter](https://stackoverflow.com/q/45368080/2943403) but honestly this looks like an [XY Problem](https://meta.stackexchange.com/q/66377/352329). If you know what column you are looking in, and you know what value that you you are looking for, then the only unknown data point is the first-level key: `[1]`. I find this question to be confused and Unclear. What are you _actually_ trying to do? – mickmackusa Dec 11 '22 at 12:29

5 Answers5

2

I would combine array_filter and array_map for this.

$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");

// filter the data
$data = array_filter($data, fn ($value) => $value['content'] === 'World');

// map the data
$data = array_map(fn ($value)  => ['content' => $value['content']], $data);

// reset indexes
$data = array_values($data);

print_r($data);

Example: https://phpize.online/s/9U

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
Ron van der Heijden
  • 14,803
  • 7
  • 58
  • 82
0

In mainFunction you are not using $myNewArray as global so it's only in the scope, but in the array_filter function you are using global $myNewArray;

$var = "test";
$myNewArray; // global array
function mainFunction() {
    global $var, $myNewArray;//if this is not present it's not global $myNewArray
    $myNewArray = array();
    $data = array("a", "b", "c");
    array_filter($data, function ($value) {
        global $myNewArray;//this uses global 
        $myNewArray[] = $value;
    });
    print_r($myNewArray); // TEST OUTPUT
}
mainFunction();

Here is an example of you code without global $myNewArray

$var = "test";    
function mainFunction($var) {
    $myNewArray = array();
    $data = array("a", "b", "c");
    $myNewArray[] = array_filter($data, function ($value) {
        return $value;
    });
    print_r($myNewArray); // TEST OUTPUT
}

mainFunction($var);

Answer to Update: You can use array_reduce to achieve that

function mainFunction() {
    global $var;
    $myNewArray = array();
    $data[] = array("id" => "1", "content" => "Hello");
    $data[] = array("id" => "2", "content" => "World");
    $myNewArray = array_reduce($data, function($accumulator, $item) {
        if ($item['content'] === "World") 
            $accumulator[] = ['content' => $item['content']];        
        return $accumulator;
    });
    print_r($myNewArray); // TEST OUTPUT
}

mainFunction();
angel.bonev
  • 2,154
  • 3
  • 20
  • 30
0

Everything seems to work fine.

<?php

$data = [];
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");

$filtered_data = array_filter($data, function($value) {
  return $value['content'] == "World";
});

print_r($filtered_data);

The output is just like expected:

Array ( [1] => Array ( [id] => 2 [content] => World ) )

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.

<?php

$data = [];
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");

$filtered_data = [];
foreach($data as $v) {
  if($v['content'] == "World")
    $filtered_data[] = ["content" => $v['content']];
}

print_r($filtered_data);

The output then would be:

Array ( [0] => Array ( [content] => World ) )

Abraham Tugalov
  • 1,902
  • 18
  • 25
0

You want two different things :

  • filter your array (keep only some elements)
  • map your array (change the value of each element)

Filter your array

On your second attempt you've done it right but array_filter callback function expect a boolean as the return value. It will determine wherever array_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 use array_map to do that.

function mainFunction() {
    $data[] = array("id" => "1", "content" => "Hello");
    $data[] = array("id" => "2", "content" => "World");
    
    $myNewArray = array_filter($data, function ($value) {
        if ($value['content'] == 'World') {
            return true;
        }
        return false;
    });
    // myNewArray contains now the willing elements, but still don't have the willing format
    /* myNewArray is [
        0 => [
            'id' => '2',
            'content' => 'World'
        ]
    ]*/
    
    $myNewArray = array_map($myNewArray, function($value){
        return [
            'content' => $value['content']
        ];
    });
    // myNewArray contains now the willing elements with the willing format
    /* myNewArray is [
        0 => [
            'content' => 'World'
        ]
    ] */

}


mainFunction();
SeeoX
  • 565
  • 3
  • 18
-1

you can use this code..........

<?php
    function test_odd($var)
      {
      return($var & 1);
      }
    
    $a1=array(1,3,2,3,4);
    print_r(array_filter($a1,"test_odd"));
    ?>
  • While this code may answer the question, [including an explanation](https://meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers) of how or why this solves the problem would really help to improve the quality of your post. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – ppwater Dec 09 '22 at 16:07