user2129623
user2129623

Reputation: 2257

pushing string into empty array gives warning

I created empty array and pushing val into it.

$var  = array();
function printTag($tags) {
        foreach($tags as $t) {
                echo $t['token'] . "/" . $t['tag'] .  " ";
                if($t['tag'] == 'NN' OR $t['tag']== 'JJ'){
                        array_push($var, $t['token'])   ;
                }
        }
        echo "\n";
}

code looks fine for me but gives error:

 array_push() expects parameter 1 to be array, null given in /var/www/html/postag/poscall.php on line 9

what is wrong here?

entire code:

<?php
// little helper function to print the results
include ("postag.php");
$var  = array();
function printTag($tags) {
        foreach($tags as $t) {
                echo $t['token'] . "/" . $t['tag'] .  " ";
                if($t['tag'] == 'NN' OR $t['tag']== 'JJ'){
                        array_push($var, $t['token'])   ;
                }
        }
        echo "\n";
}

$tagger = new PosTagger('lexicon.txt');
$tags = $tagger->tag('The quick brown fox jumped over the lazy dog. this is really yummy and excellent pizza I have seen have really in love it it');
printTag($tags);
?>

Upvotes: 0

Views: 52

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173642

The problem in your case is that $var is not in the scope of your function, so it gets implicitly declared as null (and this raises a notice too).

That said, this seems like a good case array_reduce():

$var = array_reduce($tags, function(&$result, $t) {
    if (in_array($t['tag'], ['NN', 'JJ'])) {
        $result[] = $t['token'];
    }
    // you could do some output here as well
    return $result;
}, []);

It filters and maps at the same time and the return value is the array you want.

Alternatively, just declare $var inside the function and return it:

function printTag(array $tags) 
{
    $var = [];

    foreach($tags as $t) {
        // ...
    }

    return $var;
}

// ...
$var = printTag($tags);

Upvotes: 1

Kasun Rajapaksha
Kasun Rajapaksha

Reputation: 536

Your $var = array(); statement is outside the function and out of the scope of the function. Put that inside the function and it'll remove the warning

function printTag($tags) {
   $var  = array();
   foreach($tags as $t) {
            echo $t['token'] . "/" . $t['tag'] .  " ";
            if($t['tag'] == 'NN' OR $t['tag']== 'JJ'){
                    array_push($var, $t['token'])   ;
            }
    }
    echo "\n";
}

Upvotes: 1

Related Questions