jiexi
jiexi

Reputation: 3029

How can I compare two string variables?

I have these declared

$username = $this->users->getUsernameById($file->user);
$sessionuser = $this->session->userdata('username');

How would I go about comparing to the two values and if they match, execute code? I had

if ( $username == $sessionuser){

blalghalhalhalhllahblahhblahhblahhh
}

However, even when the two variables are the same, it doesn't seem to trigger the if statement. Did I do something wrong? maybe not ==, just =?

Upvotes: 0

Views: 1237

Answers (2)

Noah Goodrich
Noah Goodrich

Reputation: 25263

Generally speaking PHP is very forgiving when it comes to comparison operations because of the loosely typed dynamic nature of the language.

Try this to debug your code:

echo $username . '<br/>' . $sessionuser;

You may find that the values you are expecting aren't actually the values you're getting.

Another thing that I frequently have to do when stepping through my code is to place something like this:

echo 'got here';
exit;

immediately inside the if block to very whether it is that the block is not executing or whether it is the code within the block that is not executing as I expected it to.

Upvotes: 2

ChssPly76
ChssPly76

Reputation: 100706

Use strcmp() function - or strcasecmp() for case-insensitive comparison.

if ( strcmp($username, $sessionuser) == 0) {

Upvotes: 2

Related Questions