Welcome Guest, Not a member yet? Register   Sign In
Undefined offset . How to rid this error?
#1

[eluser]CI-Newb[/eluser]
I am working on an activation function for user accounts. I want to structure the link in this way:
Code:
www.website.com/activation/jof9jff94j9f84jf94f-003
where everything before the dash is the activation code and everything after the dash is the user id.

Currently I am using the following piece of code to accomplish this:
Code:
$parts = explode("-",$code);
$code = $parts['0'];
$userid = $parts['1'];
if ($code != NULL && $userid != NULL && $user->exists()) {
In my check If the userid = null then it will redirect to a page saying the provided link is invalid. All of this works but when the page showing the invalid message opens I get a php error "Message: Undefined offset: 1". How can I write the code in such a way as to not receive this message or would someone have thoughts on a better way to structure the link.
#2

[eluser]CroNiX[/eluser]
check to make sure the dash is present before trying to explode on it. If it isn't, there won't be a index of 1 in $parts. Or, check to make sure isset($parts[1]) before trying to assign it to $userid.
#3

[eluser]vitoco[/eluser]
if your exploded string transforms always into a 2 position array, you can check that in 2 possible ways

Code:
$parts = explode("-",$code);

// MUST BE 2 PARTS
if( count( $parts ) != 2 )
{
    echo 'error';
    exit();
}

// CHECK SECOND POSITION : CAN BE A N > 2 POSITIONS
if( ! isset( $parts[ 1 ] ) )
{
    echo 'error';
    exit();
}

$code    = $parts[ 0 ];
$userid  = $parts[ 1 ];

if ($code != NULL && $userid != NULL && $user->exists()) {

Also, indexes assigned to the array via explode() are int, no need to put it inside ''

Saludos
#4

[eluser]CI-Newb[/eluser]
Excellent, thank you both for the replies. How does this look now:

Code:
$parts = explode("-", $code);
        if (count($parts) != 2) {
            $code = NULL;
            $userid = NULL;
        } else {
            $code = $parts[0];
            $userid = $parts[1];
        }

if both parts are not present set both to null which my check will then redirect to the error page. otherwise set them both to the appropriate variables
#5

[eluser]vitoco[/eluser]
it works, but i'm used to set defaults outside conditionals, like this
Code:
$parts = explode("-", $code);
// DEFAULTS
$code = NULL;
$userid = NULL;
// CORRECT CONDITION
if (count($parts) == 2)
{
    $code = $parts[0];
    $userid = $parts[1];          
}

Slds

#6

[eluser]wiredesignz[/eluser]
Code:
list($code, $userid) = array_pad(explode('-', $code), 2, NULL);
#7

[eluser]CI-Newb[/eluser]
@wiredesignz: Thank you very much, wonderful solution. I've just finished reading the php-manual information for list & array_pad. Smile Works like a charm much cleaner code as well




Theme © iAndrew 2016 - Forum software by © MyBB