Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting array of string to array of integers in PHP [duplicate]

Tags:

arrays

php

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

)
like image 980
Nikhil Kuriakose Avatar asked Jan 07 '17 09:01

Nikhil Kuriakose


2 Answers

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)))
like image 130
u_mulder Avatar answered Nov 13 '22 14:11

u_mulder


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

You could do this:

array_walk($numArray, function(&$x){$x = intval($x);});
like image 21
BizzyBob Avatar answered Nov 13 '22 14:11

BizzyBob