Reputation: 6569
Here's my php code
$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='others') {
global $values;
if(isset($id2)) {
$title = $values[$id];
}
elseif(empty($id2)) {
$title = $values[$id][$id2];
}
return $title;
}
when i do
echo show('php');
it shows "php hypertext processor"
but when i do
echo show('other','asp');
it doesnt work properly, it should display "active server pages"
Whats the error i am making? Can anybody help me out?
Upvotes: 0
Views: 61
Reputation: 388
Well I believe your fundamental logic is wrong: Look if you are setting both variables with a default value, this logic of urs..
if(isset($id2)) {
$title = $values[$id];
}
elseif(empty($id2)) {
$title = $values[$id][$id2];
}
Boils down to
$title = $values[$id];
Better you try to keep no default values and rebuild the logic.
Upvotes: 0
Reputation: 2620
I suspect you are always entering the first part of your if statement as you set a default value for $id2 in your function declaration and your logic is slightly wonky. Try:
function show($id='php', $id2) {
global $values;
if(isset($id2)) {
$title = $values[$id][$id2];
}
elseif(empty($id2)) {
$title = $values[$id];
}
return $title;
}
This way if $id2 is set then it should pull out from the second array and default to the first if empty.
Upvotes: 1
Reputation: 449415
You are doing the check the wrong way around.
Also, the empty
call is somewhat redundant. I would recommend this:
if(!empty($id2)) {
$title = $values[$id][$id2];
}
else {
$title = $values[$id];
}
Upvotes: 3