Andrew
Andrew

Reputation: 239097

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

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?

Upvotes: 6

Views: 2225

Answers (6)

Developer
Developer

Reputation: 26283

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 ....

Upvotes: 2

casablanca
casablanca

Reputation: 70731

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
}

Upvotes: 4

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

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"

Upvotes: 6

Misiur
Misiur

Reputation: 5307

Hm... Type casting?

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

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

Upvotes: -1

Bella
Bella

Reputation: 3217

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 }

Upvotes: 0

Artefacto
Artefacto

Reputation: 97845

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))

Upvotes: 2

Related Questions