Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 571
Andrew Avatar asked Jul 13 '10 17:07

Andrew


2 Answers

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"
like image 176
Pascal MARTIN Avatar answered Oct 14 '22 02:10

Pascal MARTIN


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
}
like image 45
casablanca Avatar answered Oct 14 '22 00:10

casablanca