#1
  1. Mad Scientist
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2007
    Location
    North Yorkshire, UK
    Posts
    3,661
    Rep Power
    4124

    Whats the fastest way to apply a function with arguments to an array of data


    I want to apply html entities to an array - which could theoretically have a large number of elements.

    When looking at looping functions I always look for a native php way of handling it as I feel that the internals of php are faster than the userland interpretted code...so I would use array_map, for example:

    PHP Code:
    $data array_map('htmlentites',$data); 
    However, I actually want to call

    PHP Code:
    htmlentites($value'ENT_QUOTES','UTF-8'); 
    on each element

    I'm currently running this in a for-each loop....but want to know if there's a faster way....and if there's a recursive way for if the array is 'multi dimensional'
    I said I didn't like ORM!!! <?php $this->model->update($this->request->resources[0])->set($this->request->getData())->getData('count'); ?>

    PDO vs mysql_* functions: Find a Migration Guide Here

    [ Xeneco - T'interweb Development ] - [ Are you a Help Vampire? ] - [ Read The manual! ] - [ W3 methods - GET, POST, etc ] - [ Web Design Hell ]
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Hi,

    use a custom function to act as a wrapper for htmlentities(). This way you also don't have to repeat the same parameters again and again:

    PHP Code:
    <?php

    function escape_html($input) {
        return 
    htmlentities($inputENT_QUOTES ENT_XHTML'UTF-8');
    }

    $data = array('a<''b>');
    $esc_data array_map('escape_html'$data);
    Starting with PHP 5.3, you can also use closures and do this JavaScript-style:

    PHP Code:
    $esc_data array_map(function ($input) {
        return 
    htmlentities($inputENT_QUOTES ENT_XHTML'UTF-8');
    }, 
    $data); 
    And there's array_walk() and array_walk_recursive().
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo