PHP increment a variable in a function. The function runs in a forloop. resets to 0?

末鹿安然 提交于 2019-12-25 02:47:33

问题


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.



来源:https://stackoverflow.com/questions/24096564/php-increment-a-variable-in-a-function-the-function-runs-in-a-forloop-resets-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!