/usr/portage

Convert an array of strings into an array of integers 4

The traditional way:

$array = array('0', '1', '2');
foreach ($array as $key => $var) {
    $array[$key] = (int)$var;
}

The nice way:

$array = array('0', '1', '2');
array_walk(&$array,
    create_function('&$value', '$value = (int)$value;');
);

Update: Another nice version with array_map():

$array = array('0', '1', '2');
$array = array_map(
    create_function('$value', 'return (int)$value;'),
    $array
);

Filed on 13-06-2007, 16:04 under , & four comments & two trackbacks

Trackbacks

Trackback specific URI for this entry

  1. Trackback from WEBLOG (Bernds Blog)
    posted on June 13th 2007, 10:30:12 pm Programmiersprachenschwanzvergleich

    Da muss ich einfach mal ein nicht geworfenes Stöckchen aufgreifen. :) Lars sagt: The nice way: $array = array(‘0’, ‘1’, ‘2’); array_walk(&$array, create_function(’&$value’, ‘$value = (int)$value;’); ); Nun, da ich PHP-code und "nice" ni

  2. Trackback from WEBLOG (blog.sdamm.de)
    posted on June 13th 2007, 11:53:12 pm Informatikerstöckchen

    Lars hat angefangen, Bernd nennt es "Schwanzvergleich", und ich mach mal weiter. Ausgangspunkt war folgendes Stück PHP-Code: $array = array(‘0’, ‘1’, ‘2’);array_walk(&$array,    create_function(’&$value’, ‘$value = (int

Comments

  1. Astro says:
    published on June 14th 2007, 04:28:21 pm *

    Boah, das kann ja keiner lesen. Und warum muss ich bei create_function() an eval() denken?

    a = %w(1 2 3)
    a.map! { |v| v.to_i }

    Aber wenn an einer Stelle die Variable ein Array aus Strings und an einer anderen aus Integern ist, dann halte ich das für keinen guten Programmierstil.

    Reply

  2. Gerd Riesselmann states:
    published on June 14th 2007, 04:39:33 pm *

    $arr = array(‘1’, ‘2’, ‘a’);

    $arr = array_map(‘intval’, $arr);

    Reply

  3. Lars Strojny returns:
    published on June 14th 2007, 05:22:30 pm *

    Das ist natürlich der Nachteil, wenn man einfach mal vergisst, dass es ja auch noch intval() gibt.

    Reply

  4. samuel supposes:
    published on August 2nd 2011, 05:47:55 am *

    Thanks for the post man..been looking for it all along

    Reply

Add a Comment & let me know what you think