Cut out a whole number, any way to do it?

Asked

Viewed 41 times

0

I need to cut an integer value to be able to use in my application, previously the field was a string in my database and now is as integer, is there any way to do this? I was doing so until then, now I came up with the need to cut an integer.

$IdUF = substr($rowData['IdMunicipio'],0,2)

Or am I saying something stupid? I need some hint.

  • 4

    subst returns another string, if you are returning the value properly, just convert to int with the function intval or add (int) in front of the function.

  • It’s like @Andersoncarloswoss said. In your case, you should convert the integer to a string using (string) before $IdUF = substr((string)$rowData['IdMunicipio'], 0, 2)

  • I appreciate the tips, I’ll run some tests.

1 answer

2


PHP is not strongly typed

$IdUF = substr($rowData['IdMunicipio'],0,2) returns a string
but case $IdUF is used in an operation as sum its value will be converted so if:

<?php
$IdUF = substr($rowData['IdMunicipio'],0,2);
//$IdUF = "10" - Str
//Quando fazemos alguma operação
$IdUF++;
//$IdUF = 11 - Int

Now if the problem is when saving in the bank the solution depends on how you are implemented.

A solution to force the value is to perform the cast or conversion, between the solutions you could:

<?php
$IdUF = (int)substr($rowData['IdMunicipio'],0,2);
//ou
$IdUF = intval(substr($rowData['IdMunicipio'],0,2));
//Dessa forma o $IdUF será sempre inteiro, caso seja retornando 
//um valor que ele não consiga converter como "olá"
// o valor de $IdUF será 0.

Browser other questions tagged

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