开发者

Need Help With PHP Function, It doesn't work when i pass value by variable

Here's a php function and it works perfectly.

$values = array(

        'php' => 'php hypertext processor',

        'other' => array(
            'html' => 'hyper text markup language',
            'css' => 'cascading style sheet',
            'asp' => 'active server pages',
        )

);


function show($id='php', $id2='') {

    global $values;

    if(!empty($id2)) {
        $title = $values[$id][$id2];
    }
    else {
         $title = $values[$id]; 
    }

    echo $title;

}

When i execute this <?php show(other,asp); ?> it displays acti开发者_开发技巧ve server pages and it works, but when i do it this way it shows an error

<?php

$lang = 'other,asp'

show ($lang);

?>

It doesn't work., Please help me out here

P.S : It works if i pass variable with single value (no commas)


If you'd like to pass it in the way you have it, maybe try using explode:

function show($id='php') {

     global $values;
     $ids = explode(',',$id);

     if(!empty($ids[1])) {
         $title = $values[$ids[0]][$ids[1]];
     }
     else {
          $title = $values[$ids[0]]; 
     }

     echo $title;

}


You can't pass two variables in one string. Your string $lang needs to be split up into two vairables:

$lang1 = 'other';
$lang2 = 'asp';

show($lang1, $lang2);


It fails because the key "other,asp" doesn't exist in $values.

In other words, it is trying to evaluate the following:

$title = $values['other,asp'];

PS, it's always useful to provide an actual error rather than saying "it doesn't work".


This is because $lang will get interpreted as a single argument, so $id2 will be 'other,asp'. You need to pass them into the function separately:

$id1 = 'other';
$id2 = 'asp';

show($id1,$id2);


P.S : It works if i pass variable with single value (no commas)

You are assigning $lang to the value 'other,asp', and then passing that sole $lang variable to the show function. There is no key named "other,asp" in your $values array.

Having a comma in the string doesn't mean you're splitting the parameters, it means you're passing a single string value. You have to "pass a variable with a single value", or do it like this for multiple parameter values:



$lang = "other";
$sub_lang = "asp";
show ($lang, $sub_lang);



You are returning one string instead of the two required... how about rewriting your function to handle them instead?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜