I followed the leads in the questions this and this.
I am trying to convert an input stream of numbers to an array of integers. The code should be self explanatory.
$handle = fopen("php://stdin","r");
print("Enter space separated numbers to be made to an array\n");
$numStream = fgets($handle);
print("Creating array from : {$numStream}\n");
//Using explode to create arrays
//now we have an array of Strings
$numArray = explode(" ", $numStream);
var_dump($numArray);
print(getType($numArray[0]));
print("\n");
array_walk($numArray, 'intval');
print(getType($numArray[1]));
print("\n");
var_dump($numArray);
print_r($numArray);
I am trying to convert the String array,
array_walk($numArray, 'intval')
The last two print blocks prints the type of an array element before and after conversion.
The output is string in both the cases
string
string
I wonder what is going on here? Possibly..
Or possibly both.
Adding the complete input and output,
$ php arrays/arrayStringToInteger.php
Enter space separated numbers to be made to an array
1 1
Creating array from : 1 1
Array
(
[0] => 1
[1] => 1
)
string
string
/home/ubuntu/workspace/basics/arrays/arrayStringToInteger.php:22:
array(2) {
[0] =>
string(1) "1"
[1] =>
string(2) "1
"
}
Array
(
[0] => 1
[1] => 1
)
You should use array_map
instead of array_walk
:
$numArray = array_map('intval', $numArray);
If you still want to use array_walk
- refer to a manual which says:
If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.
As intval
function doesn't work with references you need to wrap it in some other logics, something like:
array_walk($numArray, function(&$v){ $v = intval($v); });
// which is the same as @BizzyBob solution)))
intval()
does not set the value, it only returns the value.
You could do this:
array_walk($numArray, function(&$x){$x = intval($x);});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With