1

i try to add multiple elements to an array (in this case example1 and test1 to $allCats) but it still dont work :( can anyone explain me my mistake? or what i do wrong?

function getCats($Catlist, $name) {
   $regex = '('.implode('|', $Catlist).')';
   $success = preg_match_all($regex, $name, $matches);
   return $success ? $matches[0] : [];

}


function Cats($name, $wrongCatlist, $allCats, $Catlist) {

        $Cats = getCats($Catlist, $name);
        $Cats2 = array_unique ( $Cats );
        $Cats3 = '"'.implode('", "', $Cats2).'"'; 
        array_push($allCats, $Cats3);
}

        $name = "adidas example1 handschuhe test1 nike";
        $wrongCatlist = [
        ];
        global $allCats;
        $allCats = [
        ];
        $Catlist = [
        "example1",
        "test1"
        ];
        Cats($name, $wrongCatlist, $allCats, $Catlist);
        $allCats2 = ''.implode(', ', $allCats).'';
        echo $allCats2;

1 Answer 1

1

In PHP array is passed by value. Since you want the array $allCats to be updated the variable should get passed by reference. For that your function definition will be:

function Cats($name, $wrongCatlist, &$allCats, $Catlist) {

    $Cats = getCats($Catlist, $name);
    $Cats2 = array_unique ( $Cats );
    $Cats3 = '"'.implode('", "', $Cats2).'"'; 
    array_push($allCats, $Cats3);
}

Since pass by reference can sometimes lead to confusion, you should use return statement in function. Then the function and its call will change as below:

function Cats($name, $wrongCatlist, $allCats, $Catlist) {

    $Cats = getCats($Catlist, $name);
    $Cats2 = array_unique ( $Cats );
    $Cats3 = '"'.implode('", "', $Cats2).'"'; 
    array_push($allCats, $Cats3);
    return $allCats;
}

$allCats = Cats($name, $wrongCatlist, $allCats, $Catlist);
Sign up to request clarification or add additional context in comments.

2 Comments

but that dont add $Cats3 to $allCats when i write $echo $allCats;
$allCats is initialised as empty array. getCats returns Array ( [0] => example1 [1] => test1 ) which is then concatenated and imploded and stored in $Cats3 as "example1", "test1". This string is then pushed to $allCats empty array.

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.