user3999383
user3999383

Reputation:

Passing an array to a function

I have this PHP code in sample.php:

<html>
    <head>
       <title>
           PHP Test
       </title>
       <?php
          include "sample1.php";
       ?>
    </head>
    <body>
        <?php     
            echo "<br> ";       
            echo arrayAdder([1,2,3,4]);
            echo "<br> ";
        ?>      
    </body>
</html>

And this is my function located in sample1.php

function arrayAdder($array){
    $total = count($array);
    return $total;
}

I tried to run sample.php in my browser, but an error occurs saying:

Parse error: syntax error, unexpected '[', expecting ')' in C:\xampp\htdocs\sample.php on line 13

Whats wrong with my code?

Upvotes: 0

Views: 79

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

the array shorthand syntax is supported by PHP >= 5.4 (New features). your version might not support the syntax. check the version. and for now try this -

    <?php     
        echo "<br> ";       
        echo arrayAdder(array(1,2,3,4));
        echo "<br> ";
    ?>

Upvotes: 2

Tserkov
Tserkov

Reputation: 446

Short array syntax was added to PHP in version 5.4. You'll need to make sure you're running a version of PHP >= 5.4.

You can check by creating a script with <?php phpinfo(); ?> as its contents, or running php -v from the command line.

If you're not able to update your PHP to 5.4 or later, you can always switch back to the traditional style of defining arrays, array(1, 2 ,3 ,4).

Source: http://php.net/manual/en/migration54.new-features.php

Upvotes: 2

Related Questions