Using functions on arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
werlop
Forum Commoner
Posts: 68
Joined: Sat Mar 22, 2003 2:50 am
Location: /dev/null

Using functions on arrays

Post by werlop »

Hi, I had a thought, and I am wondering if it is possible.

Can you do something like

Code: Select all

<?php
stripslashes( $data );
?>
Where $data is an array, or do you have to run the function on each element? e.g. strip all slashes from all elements in the array in one go.

Knowing me its probably complete rubbish, but there's no harm in asking! :)
jmarcv
Forum Contributor
Posts: 131
Joined: Tue Jul 29, 2003 7:17 pm
Location: Colorado

Re: Using functions on arrays

Post by jmarcv »

werlop wrote:... Where $data is an array, or do you have to run the function on each element? e.g. strip all slashes from all elements in the array in one go.
Not rubbish. It's called array_walk. Never used it myself, but you can read up on it here:
http://www.php.net/manual/en/function.array-walk.php

You'd be surprised what you can find on that site.

I finally broke down and went on a few years back, and couldn't believe all the new time savers they stuck in there that I was wasting time writing around.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Magic quotes settngs can do it all automatically, but it's probably better off if you have a choice.

Without that, yes you have to strip each element individually, one way or another, but a user-defined function can clean up the code a bit. Another idea:

foreach and pass $array by ref:

Code: Select all

<?php
function stripper(&array)
{
    foreach ($array as $key=>$value)
    {
        $array[$key] = stripslashes($value);
    }
}

// for example:
$result = mysql_fetch_array($query);
stripper($result);

?>
Last edited by McGruff on Wed Aug 10, 2005 11:42 pm, edited 1 time in total.
User avatar
werlop
Forum Commoner
Posts: 68
Joined: Sat Mar 22, 2003 2:50 am
Location: /dev/null

Post by werlop »

Thanks to you both, it seems to me like I spend all my time cleaning up data from the database, this will help a lot! :D
Post Reply