6

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

Marius Schär
  • 336
  • 2
  • 17
  • 3
    `if ( empty ( $role_data["role_id" == 1]))` !== `if ( $role_data["role_id"] != 1)`. Your old code is: `if ( empty ( $role_data["role_id" == 1]))` -> `if ( empty ($role_data[0]) )` (Because `"role_id" == 1` = FALSE and because of type juggling = 0) – Rizier123 Jul 07 '15 at 14:07
  • @Rizier123 is correct both are different. – Alive to die - Anant Jul 07 '15 at 14:08
  • 2
    It's someone attempting to be cute and show off, while failing miserably at both. That or total cargo-cult programming – Marc B Jul 07 '15 at 14:09
  • @MarcB Look at the ` Loose comparisons with ==` table: http://php.net/manual/en/types.comparisons.php First one: `TRUE` and `"php"` and second one: `1` and `"php"` – Rizier123 Jul 07 '15 at 14:20
  • yeah, I need to go have some coffee or something... – Marc B Jul 07 '15 at 14:21
  • @MarcB I would go for a cold shower :) It's like 37°C(100°F) here. – Rizier123 Jul 07 '15 at 14:21
  • 15c/59f here due to incipient nuclear winter due to forest fire smoke haze. – Marc B Jul 07 '15 at 14:24
  • 1
    Thanks guys, I learn new stuff about php every day – Marius Schär Jul 07 '15 at 14:28
  • Regarding the comment from Rizier123, could you please provide us with some more code to find out why the author wants to find out `empty ($role_data[0])`? – Zim84 Jul 07 '15 at 14:50

1 Answers1

4

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.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96