note 98847 added to function.array-map

From: Date: Sat, 10 Jul 2010 23:43:40 +0000
Subject: note 98847 added to function.array-map
Groups: php.notes 
Request: Send a blank email to php-notes+get-170868@lists.php.net to get a copy of this message
Here's a variation on array_map() that: (1) passes the array key to the callback (2) passes a single scalar argument to the callback <?php /** An array_map which takes scalar arguments. @param $cb is a callback. It can be a simple function or an object method. @param $ara is an array to operate on. @param $args is a single argument to pass to the call back. It can be an array. */ function array_map_scalar( $cb, $ara, $args ) { $range = array(); foreach ($ara as $k => $v) { $range[$k] = call_user_func( $cb, $k, $v, $args ); } return $range; } function tag_wrap( $Key, $Value, $Args ) { $Tag = $Args[0]; $Classes = $Args[1]; return "<$Tag class='$Classes' id='$Key'>$Value</$Tag>"; } $Header = array ( 'id' => 'Id' , 'firstname' => 'First Name' , 'age' => 'Age' ); $Args = array ('th', 'goa-skin' ); $Header2 = array_map_scalar( 'tag_wrap', $Header, $Args ); echo implode( "\n", $Header2 ); // This works too. $Method = array ('html_class', 'tag_wrap'); $Header3 = array_map_scalar( $Method, $Header, $Args ); echo "\n" . implode( "\n", $Header3 ); ?> Both produce this: <th class='goa-skin' id='id'>Id</th> <th class='goa-skin' id='firstname'>First Name</th> <th class='goa-skin' id='age'>Age</th> ---- Server IP: 208.69.120.55 Probable Submitter: 66.92.147.9 ---- Manual Page -- http://www.php.net/manual/en/function.array-map.php Edit -- https://master.php.net/note/edit/98847 Del: integrated -- https://master.php.net/note/delete/98847/integrated Del: useless -- https://master.php.net/note/delete/98847/useless Del: bad code -- https://master.php.net/note/delete/98847/bad+code Del: spam -- https://master.php.net/note/delete/98847/spam Del: non-english -- https://master.php.net/note/delete/98847/non-english Del: in docs -- https://master.php.net/note/delete/98847/in+docs Del: other reasons-- https://master.php.net/note/delete/98847 Reject -- https://master.php.net/note/reject/98847 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#170868) next »