0

I'm trying to get the $keysList array out of the function, but seem be going wrong somewhere. I'm getting the error:

Passed Notice: Uninitialized string offset: 2 in C:\web\apache\htdocs\dev\case2.php on line 40 Notice: Uninitialized string offset: 1 in C:\web\apache\htdocs\dev\case2.php on line 40 Notice: Uninitialized string offset: 0 in C:\web\apache\htdocs\dev\case2.php on line 40 Output = a , a and a .

How to get this right?

<?php

$catHandle = "addCat";

function validCatKeys($catHandle,$keysList)
{

    switch($catHandle){

    case "addCat":

            $listCountryCode = 'US';
            $listUserName    = 'Norman';
            $listUserId      = '1';
            $keysList        = array($listCountryCode,$listUserName,$listUserId);
            return true;
        break;

    case "addSubCat":

        break;

    case "addElm":

        break;

    default:
       return false;
    }


}



if(validCatKeys($catHandle,$keysList = ''))
{

    echo 'Passed';
    list($a, $b, $c) = $keysList;
    echo "Output =  a $a, a $b and a $c.";

}else{echo 'Failed';
}



?>
Norman
  • 6,159
  • 23
  • 88
  • 141

3 Answers3

1
function validCatKeys($catHandle,$keysList)
{

    switch($catHandle){

    case "addCat":

            $listCountryCode = 'US';
            $listUserName    = 'Norman';
            $listUserId      = '1';
            $keysList        = array($listCountryCode,$listUserName,$listUserId);
            return $keysList;
        break;
    ....
jerdiggity
  • 3,655
  • 1
  • 29
  • 41
1

please try below code its working Demo http://codepad.viper-7.com/2Eyym1 the array $keyList is local variable and has local scope so declare it global it will work.

<?php
    $catHandle = "addCat";

    function validCatKeys($catHandle,$keysList)
    {
        global $keysList;

        switch($catHandle){

        case "addCat":

                $listCountryCode = 'US';
                $listUserName    = 'Norman';
                $listUserId      = '1';
                $keysList        = array($listCountryCode,$listUserName,$listUserId);
                return true;
            break;

        case "addSubCat":

            break;

        case "addElm":

            break;

        default:
           return false;
        }


    }



    if(validCatKeys($catHandle,$keysList = array()))
    {

        echo 'Passed';
        list($a, $b, $c) = $keysList;
        echo "Output =  a $a, a $b and a $c.";

    }else{echo 'Failed';
    }
Praveen kalal
  • 2,148
  • 4
  • 19
  • 33
1

Define the $keysList variable as passed by reference in your function definition:

function validCatKeys($catHandle,&$keysList)

(notice the &)

This will make any internal changes to the $keysList variable available outside the function.

Gareth Cornish
  • 4,357
  • 1
  • 19
  • 22