15

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..

  1. The conversion is wrong
  2. How the type is checked is wrong

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

)
3
  • 2
    can you show the output of echo "<pre/>";print_r($numArray);? show us Jan 7, 2017 at 9:06
  • @Anant added a few more input statements and their outputs Jan 11, 2017 at 4:36
  • you have already accepted answer. So if you have any problem ask a new question. Jan 11, 2017 at 4:47

2 Answers 2

48

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)))
2

intval() does not set the value, it only returns the value.

You could do this:

array_walk($numArray, function(&$x){$x = intval($x);});

Not the answer you're looking for? Browse other questions tagged or ask your own question.