Ing. Michal Hudak
Ing. Michal Hudak

Reputation: 5612

PHP merge/rewrite arrays to one by condition

I want to merge them to one where values are 1.

Example:

I have 3 arrays:

$array1 = [1,0,0,1,0];
$array2 = [0,0,0,1,0];
$array3 = [0,1,0,0,0];

There are "n" number of arrays.

So wanted output will be:

$array = [1,1,0,1,0]

More detail:

This is my basic idea of merging user permissions. Each array represents group which user is part of and each key in array is permission. Each value of array represents true/false if user have permission.

Thank you for your code / suggestions / ideas.

Upvotes: 0

Views: 108

Answers (1)

Rizier123
Rizier123

Reputation: 59691

This should work for you:

<?php

    $array1 = [1,0,0,1,0];
    $array2 = [0,0,0,1,0];
    $array3 = [0,1,0,0,0];
    $result = array();  
    $n = 3; $tmp = 0;
    $result = array();

    for($count = 0; $count < count($array1); $count++) {    
        for($i = 1; $i <= $n; $i++)
            $tmp = ${"array" . $i}[$count] || $tmp;
        $result[] = $tmp;
    }

    var_dump($result);

?>

Output:

array(5) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(false) [3]=> bool(true) [4]=> bool(false) }

Upvotes: 1

Related Questions