PHP increment a variable in a function. The functi

2019-09-18 16:32发布

问题:

Hi I have a very simple PHP function which when runs always returns the value of 1. I need to increment the value of the variable $board to 1,2,3,4,5,6 and so on. Cannot catch the error here ?

function poste() {

            $board++;
            echo $board;

            global $sourcedir;

            require_once($sourcedir . '/Subs-Post.php');

            $msgoptions = array(
                    'id' => 0,
                    'body' => 'Welcome',
                    'subject' => 'Welcome To The Boards',
            );
          $topicoptions = array(
                    'id' => 0,
                    'board' => $board,
                    'poll' => null,
                    'lock_mode' => 0,
                    'sticky_mode' => 0,
                    'mark_as_read' => false,
            );


            $posteroptions = array(
                    'update_post_count' => 1,
            );

            createPost($msgoptions, $topicoptions, $posteroptions);
    }

    for($board = 1; $board <= 3; $board++ ){
    $board++;
    echo $board;
    poste();
    }

回答1:

$board in the for loop is not the same in your function. function is "subprogram" so it's a different variable.

Use something like poste($board).

function poste($board) {

        $board++;
        echo $board;

        global $sourcedir;

        require_once($sourcedir . '/Subs-Post.php');

        $msgoptions = array(
                'id' => 0,
                'body' => 'Welcome',
                'subject' => 'Welcome To The Boards',
        );
      $topicoptions = array(
                'id' => 0,
                'board' => $board,
                'poll' => null,
                'lock_mode' => 0,
                'sticky_mode' => 0,
                'mark_as_read' => false,
        );


        $posteroptions = array(
                'update_post_count' => 1,
        );

        createPost($msgoptions, $topicoptions, $posteroptions);
}

for($board = 1; $board <= 3; $board++ ){
$board++;
echo $board;
poste($board);
}

This should work.



标签: php increment