MOS
MOS

Reputation: 31

How to restore a value of a variable after it was already changed?

I have set this code, so whenever $_GET['start'] is a number it should output the link (continue) and the value of $start will increase by 2 every time I click continue.

The question is when $_GET['start'] is not a number, then the $start variable should not be overridden. It means it should have the default value which was 2.

How can I do that ?

<?php

$number=array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g', 'j');
$start = 2;          
$len = isset($_GET['len']) ? (int)$_GET['len'] : 2; 
$s = isset($_GET['start']) ? (int)$_GET['start'] + 2 : 4; 
$count = count($number);

foreach ($number as $value) {       
    print_r($value) ; 
}

echo '<br><br>';

if (isset($_GET['start'])) {
    $start = $_GET['start'];
}


foreach (array_slice($number, $start, $len) as $k) {
    print_r($k);
}

echo '<br><br>';                                                                      

if (is_numeric($start)) {
    if ($start <= $count) {
        echo '<a href="http://192.168.1.6/alpha.php?start=' . $s . '&len=2">continue</a>'; 
    }
}

Upvotes: 0

Views: 92

Answers (2)

Amit Joshi
Amit Joshi

Reputation: 1354

Adjust your if condition as follows:

$start = 2;

if (!empty($_GET['start']) && is_numeric($_GET['start']) && !is_float($_GET['start'])) {
    $start = $_GET['start'];
}

Upvotes: 1

Blaise
Blaise

Reputation: 340

You need to check to see if $_GET['start'] is empty, and if it is not, then replace the variable. Otherwise you can just leave it as is.

Replace

    if (isset($_GET['start']))
  $start = $_GET['start'];

With

if($_GET['start']!= null){
   $start = $_GET['start'];
}

Upvotes: 0

Related Questions