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开发者_Go百科 do this comparison?
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"
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
}
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))
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 ....
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 }
Hm... Type casting?
if ((string)$permissions != '0777') {
//do something
}
I don't know will it affect on later. (LAWL I'm slowpoke)
精彩评论