how to make a substring in an int in PHP

Asked

Viewed 80 times

3

I have the following code:

$chk_selectes = $_REQUEST['chk_selectes']; 

it receives via REQUEST a variable with this value: 000 or 001 or 011 or 111.

I need to check each of these elements so I used:

$um = substr("$_REQUEST['chk_selectes']", 0,1);
$dois = substr("$_REQUEST['chk_selectes']", 1,1);
$tres= substr("$_REQUEST['chk_selectes']", 2,1);

but since the value of chk_selectes is 000 and this is an int this giving error.

I tried that already:

$chk_selectes = (string) $_REQUEST['chk_selectes']; 

2 answers

3


When you retrieve any variable that is of type integer, automatically you are transforming 001 in 1. As your default has only 3 numeric digits you can use sprintf:

sprintf('%03d', 001);

In your code:

$chk_selectes = sprintf('%03d', $_REQUEST['chk_selectes']);

$um = substr($chk_selectes, 0,1);
$dois = substr($chk_selectes, 1,1);
$tres= substr($chk_selectes, 2,1);

You can see running here.

References:

  • Just one addendum: make sure the request value is a integer. When I tested with 011 he was treated like an octadecimal, turning into 9, which resulted in 009. Behold that other answer for more details.

2

000, 001 is not int and for sure $_REQUEST['chk_selectes'] does not bring values int

If the front end in the form is actually sending exactly 000, then it will come 000, like string, so if 000 turned 0 is because there was something in between, maybe at the time of sending the FORM, Ajax, some function that affects the whole $_REQUEST.

It also seems that you are trying to extract the data, if you are sure it will always be something with 3 digits then could use [...] in the string instead of using substr

Documentation: http://php.net/manual/en/language.types.string.php#language.types.string.substr

So it sure is simpler:

$um = $chk_selectes[0];
$dois = $chk_selectes[1];
$tres = $chk_selectes[2];

var_dump($um, $dois, $tres);

IDEONE: https://ideone.com/TMryqi

I think it would be more interesting substr for when you need a "range" larger or different from the string.

  • show! really so it gets simpler than with substring rs

  • @Juliohenrique don’t forget the initial problem sprintf may have solved the problem there, but it sure doesn’t make sense $_REQUEST to bring you INT. Even if you send the number 1 via form will arrive as string in _REQUEST. The problem is something else.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.