Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing if statement in php

I'm refreshing some older code (someone else wrote), and came across this:

if ( empty ( $role_data["role_id" == 1]))

what are the reasons (if any) one would use the above instead of?:

if ( $role_data["role_id"] != 1)

IMO readability is worse and it's more code. Performance isn't a factor here.

--EDIT--

I should mention, that the expected input($role_data["role_id"]) is a number between 0 - 5 (inclusive)


--MORE INFO--

I've missunderstood the code the first time around. But here's what's happening:

$role_id = htmlspecialchars ( mysql_real_escape_string ( $_GET["role_id"] ) );
$role_data = $db->fctSelectData ( "core_role" , "`role_id` = '" . $role_id . "'" );

This goes to get the permissions for creating the role. But if given an invalid $role_id in the first place (via the $_GET parameter), it returns nothing, hence checking for an empty value in:

if ( empty ( $role_data["role_id" == 1] ) )

I'm still not fully clear of why it's written this way

like image 648
Marius Schär Avatar asked Jul 07 '15 14:07

Marius Schär


1 Answers

The line

if (empty($role_data["role_id" == 1]))

Gets translated into...

if (empty($role_data[0]))

...by the PHP interpreter. This code might be a "joke", a funny hack or an error as the line:

if (empty($role_data["role_id"]) == 1)

..sort of makes sense.

like image 154
OptimusCrime Avatar answered Oct 06 '22 20:10

OptimusCrime