EASY noob question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
briandog
Forum Newbie
Posts: 2
Joined: Sun Jun 12, 2005 8:45 pm

EASY noob question

Post by briandog »

hey all,

i'm a web designer, but my skills are all in graphics and some css. I'm trying to get into the PHP world, and when trying to write a simple code, i'm already having problems.

The funny thing is, the script runs FINE when i comment out the function. whenever i make the if/else code into the function check_link(), and then echo the check_link() function, it just shoots automatically to the "else" part of the validator. WHY?!?!?

THANKS!

Code: Select all

<?php
$page_id= 'test1';
$id_current= 'test2';
$id_active= 'test3"';

function check_link() 
{

if($page_id == 'test1')
	 {
	 echo $id_current;
	 }
elseif($page_id == 'test2')
	{
	echo $id_active;
	}
else
{
echo "everything else";
}
	
}

echo check_link();

?>
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

It helps to make your code readable:

Code: Select all

<?php
$page_id= 'test1';
$id_current= 'test2';
$id_active= 'test3"';
 
function check_link() {
    if($page_id == 'test1') {
        echo $id_current;
    }
    elseif($page_id == 'test2') {
        echo $id_active;
    }
    else {
        echo "everything else";
    }
}
 
echo check_link();
 
?>
Now then, the problem is, your function is supposed to return a value. The way your function is set up will work fine, but you need to call it as so:

Code: Select all

function check_link() {
    //....
}
 
check_link();
If you want to echo the result of the function, you need to return that value to the echo statement:

Code: Select all

function check_link() {
    if($page_id == 'test1') {
        return $id_current;
    }
    elseif($page_id == 'test2') {
        return $id_active;
    }
    else {
        return "everything else";
    }
}
 
echo check_link();
wyred
Forum Commoner
Posts: 86
Joined: Mon Dec 20, 2004 1:59 am
Location: Singapore

Post by wyred »

To the threadstarter, read up on variable scope.

Within the check_link() function, the variable $page_id does not exist. You can either declare it global or pass it in like check_link($page_id, $id_current, $id_active);
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

err.. yeah, there's that too. To let the function read that variable:

Code: Select all

function check_link() {
    global $page_id;
    //...
}
briandog
Forum Newbie
Posts: 2
Joined: Sun Jun 12, 2005 8:45 pm

much thanks

Post by briandog »

thanks very much both of you for your help, it works great after taking your advice and declaring all 3 variables global within the function
Post Reply