Home > Software design >  array_filter function in function
array_filter function in function

Time:12-09

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
        )
)

CodePudding user response:

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/sql/mysql57/undefined/php/php81/d949704f2c67d18ae6760928914b3988/

CodePudding user response:

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 ) )

CodePudding user response:

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();

CodePudding user response:

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();

CodePudding user response:

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"));
    ?>
  •  Tags:  
  • php
  • Related