Convert string number to PHP integer

5

I am converting a string to integer in PHP, however in the return of settype($variavel, "integer") , or (int)$variavel bring me a null value or equal to 1.

Is there another way to try the conversion?

The code I'm having is this:

<script type="text/html" id="javo-map-tab-infobx-content">
 <div class="btn-group btn-group-justified pull-right">
                    <a id="botaoBrief" class="btn btn-primary btn-sm" onclick="window.javo_map_tab_func.brief_run(this);" data-id="{post_id}">
                        <i class="fa fa-user"></i> <?php _e("Briefaaaa", "javo_fr"); ?>
                    </a>

<?php
$idPost = '{post_id}';

var_dump($idPost); // resultado->   string(9) "5266"

$idPost = intval($idPost); //resultado-> 0

echo gettype($idPost); //resultado-> integer
    
asked by anonymous 31.08.2015 / 21:22

3 answers

6

If you are returning 1 through intval it may be because the variable is an array. Attention to that. Make sure the variable is a string.

Example:

$variavel = '200';
$variavel = intval($variavel);

This will return: 200

If it is:

$variavel = array('foo'=>'200');

$variavel = intval($variavel);

This will return: 1

If possible, could you debug the variable here?

Debug like this:

   if(is_array($idPost))
        echo 'Array';
    else
        echo 'Not Array';

die;
    
02.09.2015 / 12:05
3

settype returns whether the variable type was successfully changed (true or 1), null, or 0 for failure. You can cast int.

<?php
   $variavel = (int) '200';
   echo gettype($variavel)
    
02.09.2015 / 14:12
2

Use the intval function.

intval("123"); // retorna 123

Documentation: link

Other functions of the same type:

boolval($val);  // retorna o valor de $val convertido para um booleano
floatval($val); // retorna o valor de $val convertido para um float
strval($val);   // retorna o valor de $val convertido para um string
    
31.08.2015 / 21:24