I have an array:
$TaxIds=array(2) { [0]=> string(1) "5" [1]=> string(2) "10" }
I need convert to this:
$TaxIds=array(2) { [0]=> int(5) [1]=> int(10) }
simple way???
I have an array:
$TaxIds=array(2) { [0]=> string(1) "5" [1]=> string(2) "10" }
I need convert to this:
$TaxIds=array(2) { [0]=> int(5) [1]=> int(10) }
simple way???
Simplified version of @george's answer would be:
$TaxIds = array_map('intval', $TaxIds);
More info at array_map
Although the question was asked a long time ago, it may be useful for someone
You can use array_map
$TaxIds = array_map(function($value) {
return intval($value);
}, $TaxIds);
array_walk($array, function(&$value, &$key) {
settype($value, "integer");
});
You could for loop it
for($i = 0; $i < count($TaxIds);$i++) {
$TaxIds[$i] = (int) $TaxIds[$i];
}
try this:
$TaxIds = ["5", "10"];
$TaxIds = array_map(function($elem) { return intval($elem); }, $TaxIds);
var_dump($TaxIds);
var_dump output:
array(2) { [0]=> int(5) [1]=> int(10) }
There are a lot of solutions to this problem. Some of them have been already posted. You can use one other solution with foreach.
foreach($TaxIds as &$taxId) {
$taxId = intval($taxId);
}
However, I don't think you need to cast it to integer. PHP will detect if you want to make numeric operation and cast it dynamically.
$TaxIds = array( "1" ,"5", "2" ,"10");
$TaxIds = array_map(function($arr) {
return intval($arr);
}, $TaxIds);
var_dump($TaxIds);
Output
array (size=4)
0 => int 1
1 => int 5
2 => int 2
3 => int 10
You could try this:
$arr = array("1", "2");
$my = json_encode($arr, JSON_NUMERIC_CHECK);
$dec = json_decode($my, true);
var_dump($dec);
Output: array(2) { [0]=> int(1) [1]=> int(2) }
Or, as others have suggested, you could use array_map:
$arr = array("1", "2");
$arr = array_map(function($value) {
return intval($value);
}, $arr);
var_dump($arr);
Output: array(2) { [0]=> int(1) [1]=> int(2) }
Edit: Use the following if you are expecting actual string in the array:
$arr = array("1", "2");
$arr = array_map(function($value) {
return is_numeric($value) ? intval($value) : $value
}, $arr);