Viewed   160 times

The following code:

$string = "1,2,3"
$ids = explode(',', $string);
var_dump($ids);

Returns the array:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}

I need for the values to be of type int instead of type string. Is there a better way of doing this than looping through the array with foreach and converting each string to int?

 Answers

1

You can achieve this by following code,

$integerIDs = array_map('intval', explode(',', $string));
Friday, September 9, 2022
4

Try explode:

$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);

Output :

Array
(
    [0] => 9
    [1] => admin@example.com
    [2] => 8
)
Monday, September 12, 2022
4

Try preg_split.

$exploded = preg_split('@/@', '1/2//3/', NULL, PREG_SPLIT_NO_EMPTY);

Thursday, September 29, 2022
 
4

Try iterating over your primary list elements.

>>> A = [['1', '2', '3', '4', '5', '6'], ['2', '3', '2', '3', '4']]
>>> [list(map(int, x[2:])) for x in A]
[[3, 4, 5, 6], [2, 3, 4]]

Calling list() forces Python 3 to fully evaluate the map - it's not necessary in Python 2.

Tuesday, August 9, 2022
 
1

Did you notice there are two std::cout in the function itself?

Beside that also add this:

stream->str(""); //This ensures that the stream is empty before you use it.
(*stream)<<string;

By the way, why don't you use boost::lexical_cast?

int IntegerTransformer::transformFrom(std::string s){
     return boost::lexical_cast<int>(s);
}
Friday, September 30, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :