Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function in PHP akin to substr() for integers?

Tags:

php

int

substr

I have a phone number which will be recorded as an int (e.g 1234512312345) on my database but which I would like to represent as (12345) 123 - 12345 on a webpage. If it was a string I would use substr but it seems inelegant to convert it to a strval.

While I appreciate that integers and strings are categorically distinct, is there a means to do something to this effect without writing a less-than efficient function myself?

like image 416
Jay Edwards Avatar asked Nov 30 '22 04:11

Jay Edwards


1 Answers

You can try vprintf or vsprintf with sscanf

$data = 1234512312345;
vprintf("(%d)-%d-%d",sscanf($data, "%5d%3d%5d"));

Output

(12345)-123-12345

Multiple PHP Version Test

*Note

If you want to return it has a value then it should be

$var = vsprintf("(%d)-%d-%d",sscanf($data, "%5d%3d%5d"));
        ^
        |---- Note the `s`
like image 181
Baba Avatar answered Dec 05 '22 02:12

Baba