0

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);
?>

2 Answers 2

1

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";
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);

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.