简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM