PHP: How to convert 0777 (octal) to string?

I have an octal number that I use to set permissions in 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 make this comparison?

+6
php
source share
6 answers

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

Like this:

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


However, to convert the value to a string containing the octal representation of the number, you can use sprintf and the o specifier.

For example, the following part of the code:

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

You'll get:

 string(4) "0777" 
+6
source share

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

 if (intval($expectedPermissions, 8) != $permissions) { // 8 specifies octal base for conversion // do something } 
+4
source share

The best way:

 if (0777 != $permissions) 

PHP recognizes octal literals (as your job shows).

However, you can also compare strings instead of integers:

 if ('0777' != "0" . sprintf("%o", $permissions)) 
+2
source share

Check out the base_convert function.

octal string representation of a number

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

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

+2
source share

Just enter an integer like this:

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

There is also another way that sets $ permissions in double quotes, which also makes PHP recognize it as a string:

 if('0777' != "$permissions") { // do something } 
0
source share

Hm ... Type of casting?

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

I do not know if this will affect later. (LAWL I'm slow)

-one
source share

All Articles