how to make a substring in an int in PHP

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 as the value of chk_selectes is 000 and this is an int this is giving error.

I've tried this:

$chk_selectes = (string) $_REQUEST['chk_selectes']; 
    
asked by anonymous 09.05.2018 / 20:58

2 answers

3

When you retrieve any variable that is of type integer , you are automatically transforming 001 to 1 . Since 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 working here .

References:

09.05.2018 / 21:17
2

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

If the front-end in form is actually sending 000 , then 000 will arrive, as string, so if 000 turned 0 is because there was something in the middle of it, maybe at the moment to send FORM, Ajax, some function that affects all $_REQUEST .

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

  

Documentation: link

So it sure is simpler:

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

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

IDEONE: link

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

    
09.05.2018 / 21:47