skip to Main Content

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


  1. 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();
    
    Login or Signup to reply.
  2. 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
    )
    )

    Login or Signup to reply.
  3. 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"));
        ?>
    
    Login or Signup to reply.
  4. 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

    Login or Signup to reply.
  5. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search