2

I have an array like below.

$a = array(
            array("id" => 1, "name" => "njx", "count" => 0),
            array("id" => 2, "name" => "peter", "count" => 4),
            array("id" => 3, "name" => "jeffry", "count" => 2),
            array("id" => 4, "name" => "adam", "count" => 6)
          );

and applied filter like this.

$fa = array_filter($a, function ($item) {
    return ($item["count"] > 0);
});

then i applied usort on variable $fa. After that i loop through $fa and assigned some values, but they are not get reflected in variable $a.

something like below,

usort($fa, 'comp');

foreach ($fa as &$t) {
    $t["score"] = 120;
}

var_dump($a); //this doesn't contain "score" field.

So my questions is how to get filtered array with original array reference?

10
  • use $a = array_filter($a, ...... Commented Nov 13, 2013 at 10:47
  • no. then i will lose items having count < 0. i need them. Commented Nov 13, 2013 at 10:48
  • 1
    It would be more easy for others to understand if you show a snippet of output you want. Commented Nov 13, 2013 at 10:48
  • 1
    As long as array_filter will preserve keys, you could do foreach($fa as $faKey=>$dummy) $a[$faKey]['score']=120; Commented Nov 13, 2013 at 10:57
  • So it needs another loop over $fa and assign score based on id check? Can't i get filtered array that still hold reference to $a? Commented Nov 13, 2013 at 11:01

1 Answer 1

4

array_filter returns a new array and not a reference, thats why any changes applied to $fa wont be reflected in $a.

Instead of using array_filter you could use a foreach loop like this:

foreach($a as &$t) {
    if($t['count'] > 0) {
        $t['score'] = 120;
    }
}

And then sort using usort.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.