tags:

views:

96

answers:

6

I have an octal that I am using to set permissions on a directory.

$permissions = 0777;
mkdir($directory, $permissions, true)

And I want to compare it to a string

$expectedPermissions = '0777'; //must be a string
if ($expectedPermissions != $permissions) {
    //do something
}

What would be the best way to do this comparison?

A: 

The best way is:

if (0777 != $permissions)

PHP recognizes octal literals (as your assignment shows).

That said, you could also compare strings instead of integers with:

if ('0777' != "0" . sprintf("%o", $permissions))
Artefacto
A: 

Simply cast the integer like so:

if('0777' != (string)$permissions) { // do something }

There is also another way putting $permissions in double quotes will also make PHP recognise it as a string:

if('0777' != "$permissions") { // do something }
DRL
This won't work; `(string) $permissions` will give `511`.
Artefacto
Why will it give 511?
Erik Escobedo
$permissions is not an integer, it's an octal
Andrew
@andrew take a look at http://uk3.php.net/manual/en/function.mkdir.php and you will see that mkdir() expects an int
DRL
A: 

Hm... Type casting?

if ((string)$permissions != '0777') {
//do something
}

I don't know will it affect on later. (LAWL I'm slowpoke)

Misiur
+1  A: 

Why not, in your case, just compare the two numerical values ?

Like this :

if (0777 != $permissions) {
    //do something
}


Still, to convert a value to a string containing the octal representation of a number, you could use sprintf, and the o type specifier.

For example, the following portion of code :

var_dump(sprintf("%04o", 0777));

Will get you :

string(4) "0777"
Pascal MARTIN
I don't think that is what he is looking for. This is in regards to unix permissions. 0777 would equate to a+rwx
Brent Baisley
+3  A: 

Do it the other way round: convert the string to a number and compare the numbers:

if (intval($expectedPermissions, 8) != $permissions) { // 8 specifies octal base for conversion
  // do something
}
casablanca
A: 

Check base_convert function.

octal string representation of a number

$str = base_convert((string) 00032432, 10, 8);

you can do the conversion with any type hex, octal ....

Ghost