learner
learner

Reputation: 4818

Converting comma-separated string of single-quoted numbers to int array

I have a string:

'24','27','38'

I want to convert it:

(
    [0] => 24
    [1] => 27
    [2] => 38
)

The conversion: https://3v4l.org/oDPDl

array_map('intval', explode(',', $string))

gives:

Array
(
    [0] => 0
    [1] => 0
    [2] => 0
)

Basically, array_map() works when the numbers aren't quoted like `24,27,38', but I need a technique that works with quoted numbers.

One solution is looping over the array, but I don't want to do that. Can I achieve the above using only php functions (not control structures -- e.g. foreach())?

Upvotes: 0

Views: 1525

Answers (4)

Tor2r
Tor2r

Reputation: 46

Without looping:

$str= "'24','27','38'";
$arr = array_map("intval", explode(",", str_replace("'", "", $str)));
var_dump($arr);

Output:

array(3) {
  [0]=>
  int(24)
  [1]=>
  int(27)
  [2]=>
  int(38)
}

Upvotes: 0

mickmackusa
mickmackusa

Reputation: 47991

sscanf() can instantly return type-cast values if you ask it to.

Here is a technique that doesn't use an explicit loop: sscanf(preg_replace())

Code: (Demo)

var_export(sscanf($string, preg_replace('/\d+/', '%d', $string)));

Output:

array (
  0 => 24,
  1 => 27,
  2 => 38,
)

Or some developers might find this more professional/intuitive (other will disagree): (Demo)

var_export(filter_var_array(explode("','", trim($string, "'")), FILTER_VALIDATE_INT));
// same output as above

or perhaps this alternative which leverages more commonly used native functions:

var_export(
    array_map(
        function($v) {
            return (int)$v;
        },
        explode("','", trim($string, "'"))
    )
);

which simplifies to:

var_export(array_map('intval', explode("','", trim($string, "'"))));
// same output as above

For anyone who doesn't care about the datatype of the newly generated elements in the output array, here are a few working techniques that return string elements: (Demo)

var_export(explode("','", trim($string, "'")));

var_export(preg_split('/\D+/', $string, -1, PREG_SPLIT_NO_EMPTY));

var_export(preg_match_all('/\d+/', $string, $m) ? $m[0] : []);

var_export(filter_var_array(explode(',', $string), FILTER_SANITIZE_NUMBER_INT));

Upvotes: 0

diavolic
diavolic

Reputation: 722

  $arr = explode (",", str_replace("'", "", $str));
   foreach ($arr as $elem) 
      $array[] = trim($elem) ;

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

Use the following approach:

$str = "'24','27','38'";
$result = array_map(function($v){ return (int) trim($v, "'"); }, explode(",", $str));

var_dump($result);

The output:

array(3) {
  [0]=>
  int(24)
  [1]=>
  int(27)
  [2]=>
  int(38)
}

Upvotes: 3

Related Questions