I am trying to make a $_SESSION array that takes multiple array items from a $_SESSION button when clicked. I am able to output the total array length, as well as the current number of clicks.

However, I cannot seem to be able to display the clicks in order. For example, here is my output:

Array ( [0] => 3 [1] => 3 [2] => 3 ) 3 

3 is the number of clicks, with 3 outside of () being the counter. How can I make it so my array looks like this?

Array ( [0] => 1 [1] => 2 [2] => 3 ) 3 

Here is my code:

    // Keeps track of the amount of clicks
    // The array itself
    $_SESSION['Counter'] = array($_SESSION['Counter_Value']);

    // keeps the array from being empty
    if(empty($_SESSION['Counter_Value'])) {
                $_SESSION['Counter_Value'] = 0;
// This is the code for the button
if(isset($_POST['Btn1'])) {
        // Adds to the value of the counter
        // Every time a button is clicked, its value goes to the $_SESSION array'
        array_push($_SESSION['Counter'], $_SESSION['Counter_Value']);

// On Main Page
        // This outputs $_SESSION['Counter'] and displays first 3 results
        $_SESSION['Counter'] = array_fill(0,3,$_SESSION['Counter_Value']);
        // prints out array
        // prints out amount of clicks
        echo $_SESSION['Counter_Value'];
  • where in the files are you calling the session functions and setting the values? More specifically, what makes this a WordPress question and not a generic PHP question? Might this have been better asked at stackoverflow where more PHP coders could help?
    – Tom J Nowell
    Apr 4, 2023 at 16:29
  • I am doing this all inside of a wp shortcode inside of a function. I would assume that Wordpress Stack Exchange specializes with PHP problems, as PHP is integral part of Wordpress. I am open to any suggestions.
    – John Lyons
    Apr 4, 2023 at 16:48
  • you can't start sessions from inside shortcodes, sessions have to be started before there is HTML output. Questions here should be specific to WordPress though, by that logic Joomla questions are ok on this stack because Joomla is written in PHP, which isn't the case. You need to edit your question to mention the shortcode as that's critical information.
    – Tom J Nowell
    Apr 4, 2023 at 20:17
  • also note that any form of caching will render this useless, and shortcodes aren't just rendered on the page, they're rendered in REST API requests, AJAX handlers, RSS feeds, etc. BTW if you know Counter_Value then there is no point storing Counter as you can recreate it from Counter_Value by counting backwards to zero. Most WP hosts don't support PHP sessions either, and you can't use them to avoid cookies as PHP sets a session ID cookie to identify which session belongs to the user.
    – Tom J Nowell
    Apr 4, 2023 at 20:19


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.