Search code examples
phparraysarraylistsubmitarray-key

PHP - change/adding numerical value to array key value using submit button


I am using array to limit the results from glob(), like a pagination

$show = array(5,10,15,20);

$directories = glob(__DIR__.'/*', GLOB_ONLYDIR);
$directories = array_slice($directories, 0, $show[0]); // shows first 5 folders

How can I add value of 1 to $show[0] using a button?

if(isset($_POST['submit'])){
  
  echo 'click submit to show 10 items, click again to show 15 items and so on';
  
};

Solution

  • You'll need to record the current state of the page in some way. You can do this with a hidden variable, however I would recommend either switching to $_GET for this function, or simply using a query string (as I've done here). That way you can go to the correct pagination directly in the browser URL bar.

    PHP code:

    $show = array(5,10,15,20);
    $current_page = 1; // this could also be 0 but setting it to 1 makes 'sense' to humans
    
    if(isset($_GET['page']) && (int)$_GET['page'] > 0) {
        $current_page = $_GET['page']; // first set what the current page is
    
        if(isset($_POST['submit'])) {
            // since we know the submit button increments the page count only one direction, we can use this and simply...  Increment the current page :)
            $current_page++;
        }
    } 
    
    $directories = glob(__DIR__.'/*', GLOB_ONLYDIR);
    $directories = array_slice($directories, 0, ($show[$current_page] - 1)); // shows first 5 folders ---- the "- 1" here is because we set $current_page to 1 above instead of 0.
    

    Then you can do something like this for the HTML form (using the query string method I mentioned)

    <form method="POST" action="?page=<?php echo $current_page; ?>">
        <input type="submit" name="submit" value="Submit!">
    </form>