Question

I want to fill an empty array by using the function array_push, but I got an error that parameter 1 expected to be array but null is given in, here is my code :

public $docs = array("ant ant bee", "dog bee dog hog dog ant dog", "cat gnu eel fox");

public function terms(){

    $temp = array();
    $terms = array(array());
    $docs = $this->docs;

    for($i = 0; $i < sizeof($docs); $i++){

        $temp[$i] = preg_split('/ /', $docs[$i], null, PREG_SPLIT_NO_EMPTY);
    }           

    for($i = 0; $i < sizeof($temp); $i++){

        for($j = 0; $j < sizeof($temp[$i]); $j++){

            for($k = 0; $k < sizeof($temp[$i]); $k++){

                if($temp[$i][$j] != $terms[$i][$k])

                    array_push($terms[$i], $temp[$i][$k]);
            }
        }
    }

    return $terms;
}
}
Was it helpful?

Solution

Based on your comment about expected result, this should do it or be extremely close:

foreach($this->docs as $value) {
    $terms[] = array_unique(array_filter(explode(' ', $value)));
}    
return $terms;

OTHER TIPS

I am not sure what you are doing exactly with all those loops, but your current problem is easily solved by changing:

array_push($terms[$i], $temp[$i][$k]);

to:

$terms[$i][] = $temp[$i][$k];

This does the same thing as array_push() with the difference that $terms[$i] is automatically created if it does not exist yet.

it can be achieved as follow

function terms(){   
    $docs = array("ant ant bee", "dog bee dog hog dog ant dog", "cat gnu eel fox");
    $temp = array();
    $terms = array();

    for($i = 0; $i < sizeof($docs); $i++){
        $temp[$i] = preg_split('/ /', $docs[$i], null, PREG_SPLIT_NO_EMPTY);
    } 
    foreach ($temp as $key => $value) {
        $temp[$key] = array_unique($value); 
    } 
    return $temp; 
}

Not sure that the declaration $terms = array(array()); does what you want....

Solution 1: initialize $terms first

$terms = array();

for($i = 0; $i < sizeof($docs); $i++){
    $terms[$i] = array();
}

Or better: Insert

$terms[$i] = array();

into your existing loop: either the loop where you initialize $temp, or the second for($i...) loop, just before for($j ...)

Solution 2: test terms[$i] before using array_push

for ($i ...) {
    for ($j ...) {
        for ($k ...) {
            if (!is_array($terms[$i])) $terms[$i] = array();
            // your stuff here
        }
    }
}

But I prefer the 1st solution...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top