Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unset session data by page number upto n pages in Codeigniter?

$this->session->unset_userdata('current_page_'.$pagenumber);

by using this code i am unsetting data from session for each page number but the issue is at certain point i do not know how many pages data exist in session e.g:

$this->session->unset_userdata('current_page_'.1);
$this->session->unset_userdata('current_page_'.2);
$this->session->unset_userdata('current_page_'.3);
$this->session->unset_userdata('current_page_'.4);
.
.
.
$this->session->unset_userdata('current_page_'.?????);

is there any way to unset data from session where key like "current_page_%" Thanks in advance.


1 Answers

You can try searching the initials (which is current_page_) of the session and unset accordingly.

<?php
function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}

foreach($this->session->all_userdata() as $key => $value)
{
    if(startsWith($key, 'current_page_'))
        $this->session->unset_userdata($key);
}


For example:

<?php
function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}

$session = array(
            'current_page_12' => 'abc', 
            'current_page_qw1' => 'xyz', 
            'hello' => 'world', 
            'current_page_23d' => 'mno', 
            'example' => '112'
        );

foreach($session as $key => $value)
{
    if(startsWith($key, 'current_page_'))
        unset($session[$key]);
}

print_r($session);


Output:

Array
(
    [hello] => world
    [example] => 112
)


Demo:
http://3v4l.org/uh4HK

like image 151
Parag Tyagi Avatar answered Dec 01 '25 02:12

Parag Tyagi