Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with PHP Octals and String conversions

Tags:

string

php

octal

I'm working with a database that has a bunch of serial numbers that are prefixed with leading 0's.

So a serial number can look like 00032432 or 56332432.

Problem is with PHP I don't understand how the conversion system with octals works.

A specific example is that I'm trying to convert and compare all of these integer based numbers with strings.

Is it possible to convert an octal, such as 00234 to a string like "00234" so that I can compare it?

edit - adding a specific example. I would like to be able to run str functions on the serial like below.

  $serial = 00032432; // coming from DB

  if(substr($serial, 0, 1) == '0') {

        // do something

   } 
like image 411
krx Avatar asked Mar 22 '10 20:03

krx


3 Answers

When you convert with (string) $number, you always get a string in decimal base, it doesn't matter if you write the number in octal mode or in decimal mode, an int is an int and it has not itself a base. It's his string representation that have to be interpreted with a base.

You can get the octal string representation of a number in this way:

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

or giving the number in decimal rep:

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

or, more concisely but less clearly:

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

In the last the string conversion is made implicitly. The examples give all as result $str = "32432".

base_convert converts a string representation of a number from a base to another

If you want also the zeros in your string, you can add them with simple math.

Hope this can help you.

like image 180
Nicolò Martini Avatar answered Oct 11 '22 05:10

Nicolò Martini


To convert an octal to a string, cast it:

$str = (string) 00032432;

You can convert between octal and decimal with the functions octdec and decoct

<?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?>

http://uk.php.net/manual/en/function.octdec.php

like image 28
Adam Hopkinson Avatar answered Oct 11 '22 06:10

Adam Hopkinson


$str = sprintf('%o', $octal_value);
like image 31
ya.teck Avatar answered Oct 11 '22 05:10

ya.teck