473,801 Members | 2,366 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

array_walk - userdata as array by ref

here's a quirk i can't seem to handle, just hack. since call-time
by-reference is depreciated and i don't want to enable it in the php.ini,
i'm kind of stuck when i want to pass userdata as an array byref that is
initially = array().

// the array being walked
$numbers = array(1, 56, 999, 1000, 28, 65);

// the work-around

// the callback
function validateInput(& $value, $key, &$errors)
{
$maxValue = 999;
if ($value <= $maxValue) return;
$errors[1][$key] = 'Element ' . $key. ' must be a whole number between 0
and ' . $maxValue . '.';
}
// the hack
$error = array();
$errors = array('', &$error);
array_walk($num bers, 'validateInput' , $errors);
$errors = $errors[1];
print_r($errors );

// what i'd like to do

// the callback
function validateInput(& $value, $key, &$errors)
{
$maxValue = 999;
if ($value <= $maxValue) return;
$errors[$key] = 'Element ' . $key. ' must be a whole number between 0 and
' . $maxValue . '.';
}
$errors = array();
array_walk($num bers, 'validateInput' , $errors);
print_r($errors );
it seems as though php doesn't allocate memory for $errors when it is
defined as an empty array since it has no data (!isset), and therefore
there's a pointer to nothing (figuratively). i assume since $errors =
array('', &$error) allocates memory for the structure, the callback then has
something to work on. the '' being what actually triggers allocation (makes
room for \0 i guess). that was my reasoning when i came up with the hack,
but i'd like to know for sure.

does that sound about right? suggestions on getting the results i looking
for?

tia,

me

Apr 20 '07 #1
12 2961
Steve wrote:
here's a quirk i can't seem to handle, just hack. since call-time
by-reference is depreciated and i don't want to enable it in the php.ini,
i'm kind of stuck when i want to pass userdata as an array byref that is
initially = array().

// the array being walked
$numbers = array(1, 56, 999, 1000, 28, 65);

// the work-around

// the callback
function validateInput(& $value, $key, &$errors)
{
$maxValue = 999;
if ($value <= $maxValue) return;
$errors[1][$key] = 'Element ' . $key. ' must be a whole number between 0
and ' . $maxValue . '.';
}
// the hack
$error = array();
$errors = array('', &$error);
array_walk($num bers, 'validateInput' , $errors);
$errors = $errors[1];
print_r($errors );

// what i'd like to do

// the callback
function validateInput(& $value, $key, &$errors)
{
$maxValue = 999;
if ($value <= $maxValue) return;
$errors[$key] = 'Element ' . $key. ' must be a whole number between 0 and
' . $maxValue . '.';
}
$errors = array();
array_walk($num bers, 'validateInput' , $errors);
print_r($errors );
it seems as though php doesn't allocate memory for $errors when it is
defined as an empty array since it has no data (!isset), and therefore
there's a pointer to nothing (figuratively). i assume since $errors =
array('', &$error) allocates memory for the structure, the callback then has
something to work on. the '' being what actually triggers allocation (makes
room for \0 i guess). that was my reasoning when i came up with the hack,
but i'd like to know for sure.

does that sound about right? suggestions on getting the results i looking
for?

tia,

me
Both of the code you posted did not work on my box (php5.2) unmodified.

My initial thought will be using foreach on the array $numbers, but you
might have your own reason not to use it.
Hendri Kurniawan
Apr 20 '07 #2
| Both of the code you posted did not work on my box (php5.2) unmodified.
|
| My initial thought will be using foreach on the array $numbers, but you
| might have your own reason not to use it.

i usually do. however, i'm prototyping something. here's what gives me the
results...in case my free-handed post is why it doesn't work on your box.
thanks for looking at it. sorry for the text-wrapping here...if you just
backspace the wrap, it should be very easy to read/follow.

<?
$inputs['Personnel'] = array(
'bodyTech' =0 ,
'bodyTechAppr' =0 ,
'paintTech' =0 ,
'paintTechAppr' =0 ,
'paintPreps' =0 ,
'mechanicTechs' =0 ,
'estimators' =0 ,
'otherEmployees ' =0
);
$inputs['Facility'] = array(
'bodyShopLocati on' ='' ,
'franchises' ='' ,
'totalSqFeet' =0 ,
'productionSqFe et' =0 ,
'totalWorkStati ons' =0 ,
'totalPaintBoot hs' =0 ,
'totalDetailSta lls' =0
);
function retrieveInput(& $value, $key, $source)
{
$default = 0;
if ($key == 'bodyShopLocati on'){ $default = ''; }
if ($key == 'franchises'){ $default = ''; }
$value = isset($source[$key]) ? $source[$key] : $default;
}
function validateInput(& $value, $key, &$errors)
{
$inputName = '';
$maxValue = 999;
switch ($key)
{
case 'bodyShopLocati on' : if (in_array($valu e, array('', 'ON SITE',
'OFF SITE'))){ return; }
$errors[$key] = 'BODY SHOP LOCATION must be
either on-site or off-site.';
return;
break;
case 'franchises' : if (in_array($valu e, array('', 'SINGLE',
'MULTIPLE'))){ return; }
$errors[$key] = 'FRANCHISE TYPE must be
either single or multiple.';
return;
break;
case 'bodyTech' : $inputName = 'BODY TECHNICIANS';
break;
case 'bodyTechAppr' : $inputName = 'BODY TECHNICIAN APPRENTICES';
break;
case 'paintTech' : $inputName = 'PAINT TECHNICIANS';
break;
case 'paintTechAppr' : $inputName = 'PAINT TECHNICIAN APPRENTICES';
break;
case 'paintPreps' : $inputName = 'PAINT PREPS';
break;
case 'mechanicTechs' : $inputName = 'MECHANICAL TECHNICIANS';
break;
case 'estimators' : $inputName = 'ESTIMATORS';
break;
case 'otherEmployees ' : $inputName = 'OTHER EMPLOYEES';
break;
case 'totalSqFeet' : $inputName = 'TOTAL SQUARE FEET';
$maxValue = 9999999; break;
case 'productionSqFe et' : $inputName = 'PRODUCTION AREA SQUARE FEET';
$maxValue = 9999999; break;
case 'totalWorkStati ons' : $inputName = 'TOTAL WORK STATIONS';
break;
case 'totalPaintBoot hs' : $inputName = 'TOTAL PAINT BOOTHS';
break;
case 'totalDetailSta lls' : $inputName = 'TOTAL DETAIL STALLS';
break;
default : return; break;
}
if ($value <= $maxValue) return;
$errors[1][$key] = $inputName . ' must be a whole number between 0 and ' .
$maxValue . '.';
}
array_walk($inp uts['Personnel'], 'retrieveInput' , $_REQUEST);
array_walk($inp uts['Facility'], 'retrieveInput' , $_REQUEST);
$error = array();
$errors = array('', &$error);
array_walk($inp uts['Personnel'], 'validateInput' , $errors);
array_walk($inp uts['Facility'], 'validateInput' , $errors);
$errors = count($errors) 1 ? $errors[1] : array();
echo '<pre>' . print_r($inputs , true) . '</pre>';
echo '<pre>' . print_r($errors , true) . '</pre>';
?>
Apr 20 '07 #3
Steve wrote:
| Both of the code you posted did not work on my box (php5.2) unmodified.
|
| My initial thought will be using foreach on the array $numbers, but you
| might have your own reason not to use it.

i usually do. however, i'm prototyping something. here's what gives me the
results...in case my free-handed post is why it doesn't work on your box.
thanks for looking at it. sorry for the text-wrapping here...if you just
backspace the wrap, it should be very easy to read/follow.
<SNIPPED CODE>

Umm.. again sorry if this is not the answer you are looking for.
This is what i came up with (see bottom of page)

What it basically does is that it replaces the array_walk to normal
function. Inside the function, instead of returning after correctly
validating the input, I've put "continue".

At the end i returned the errors array.
Hendri Kurniawan

<?
$inputs['Personnel'] = array(
'bodyTech' =0 ,
'bodyTechAppr' =0 ,
'paintTech' =0 ,
'paintTechAppr' =0 ,
'paintPreps' =0 ,
'mechanicTechs' =0 ,
'estimators' =0 ,
'otherEmployees ' =0
);
$inputs['Facility'] = array(
'bodyShopLocati on' ='' ,
'franchises' ='' ,
'totalSqFeet' =0 ,
'productionSqFe et' =0 ,
'totalWorkStati ons' =0 ,
'totalPaintBoot hs' =0 ,
'totalDetailSta lls' =0
);
function retrieveInput(& $value, $key, $source)
{
$default = 0;
if ($key == 'bodyShopLocati on'){ $default = ''; }
if ($key == 'franchises'){ $default = ''; }
$value = isset($source[$key]) ? $source[$key] : $default;
}
function validateInput($ value)
{
$inputName = '';
$maxValue = 999;
$errors = array();
foreach($value as $key=>$value) {
switch ($key)
{
case 'bodyShopLocati on' :
if (in_array($valu e, array('', 'ON SITE', 'OFF SITE'))){ continue; }
$errors[$key] = 'BODY SHOP LOCATION must be either on-site or
off-site.';
continue;
break;
case 'franchises' :
if (in_array($valu e, array('', 'SINGLE', 'MULTIPLE'))){ continue; }
$errors[$key] = 'FRANCHISE TYPE must be either single or multiple.';
continue;
break;
case 'bodyTech' : $inputName = 'BODY TECHNICIANS';
break;
case 'bodyTechAppr' : $inputName = 'BODY TECHNICIAN APPRENTICES';
break;
case 'paintTech' : $inputName = 'PAINT TECHNICIANS';
break;
case 'paintTechAppr' : $inputName = 'PAINT TECHNICIAN APPRENTICES';
break;
case 'paintPreps' : $inputName = 'PAINT PREPS';
break;
case 'mechanicTechs' : $inputName = 'MECHANICAL TECHNICIANS';
break;
case 'estimators' : $inputName = 'ESTIMATORS';
break;
case 'otherEmployees ' : $inputName = 'OTHER EMPLOYEES';
break;
case 'totalSqFeet' : $inputName = 'TOTAL SQUARE FEET';
$maxValue = 9999999; break;
case 'productionSqFe et' : $inputName = 'PRODUCTION AREA SQUARE FEET';
$maxValue = 9999999; break;
case 'totalWorkStati ons' : $inputName = 'TOTAL WORK STATIONS';
break;
case 'totalPaintBoot hs' : $inputName = 'TOTAL PAINT BOOTHS';
break;
case 'totalDetailSta lls' : $inputName = 'TOTAL DETAIL STALLS';
break;
default : continue; break;
}
if ($value <= $maxValue) continue;
$errors[$key] = $inputName . ' must be a whole number between 0 and ' .
$maxValue . '.';
}

return $errors;
}

array_walk($inp uts['Personnel'], 'retrieveInput' , $_REQUEST);
array_walk($inp uts['Facility'], 'retrieveInput' , $_REQUEST);
$errors = array();
$errors = array_merge($er rors,validateIn put($inputs['Personnel']));
$errors = array_merge($er rors,validateIn put($inputs['Facility']));
echo '<pre>' . print_r($inputs , true) . '</pre>';
echo '<pre>' . print_r($errors , true) . '</pre>';
?>
Apr 20 '07 #4

"Hendri Kurniawan" <as****@email.c omwrote in message
news:13******** *****@corp.supe rnews.com...

thanks hendri. btw, i didn't know you could do:

foreach($value as $key=>$value)

and expect to have the first $value preserved. i suppose though, thinking
about it, php gets a single reference to the $value array and then works off
the stack at that address. the second $value should be a new copy of the
element at $key - the next loop still working from the old stack and not the
new value of $value.

it's not so much that i want an alternative, it's that i want to understand
exactly why the hack works yet the straight-forward approach does not - even
though the docs say it should. i'm just using array_walk to benchmark
data-retrieval in a custom db class...rather than using a foreach on the
records returned, i'd be trying to walk the records - goal being to
standardize access methods, i.e. $records[0]['FOO'] as the structure...a row
and field as keys. the foreach is pretty fast over 200K rows...just wanna
see how much faster the native iteration is over the native enumeration. :)
i'm just wierd like that.

anyway, the code i posted here was me just playing with array_walk in a
practical scenario. just trying to find out about what all i could do with
the userdata param. that's when i ran into this bit of undefined behavior.
and, isn't it wonderful that it is undefined yet a single character's
correction would fix the problem - that character being '&' as a call-time
by-reference.

thanks for the help.
Apr 20 '07 #5
Steve wrote:
| Both of the code you posted did not work on my box (php5.2) unmodified.
|
| My initial thought will be using foreach on the array $numbers, but you
| might have your own reason not to use it.

i usually do. however, i'm prototyping something. here's what gives me the
results...in case my free-handed post is why it doesn't work on your box.
thanks for looking at it. sorry for the text-wrapping here...if you just
backspace the wrap, it should be very easy to read/follow.

Also forgot to mention that posted code also doesn't work.
(You might have found a bug?? :D )

Hendri Kurniawan
Apr 20 '07 #6
Steve wrote:
"Hendri Kurniawan" <as****@email.c omwrote in message
news:13******** *****@corp.supe rnews.com...

thanks hendri. btw, i didn't know you could do:

foreach($value as $key=>$value)

and expect to have the first $value preserved. i suppose though, thinking
about it, php gets a single reference to the $value array and then works off
the stack at that address. the second $value should be a new copy of the
element at $key - the next loop still working from the old stack and not the
new value of $value.

it's not so much that i want an alternative, it's that i want to understand
exactly why the hack works yet the straight-forward approach does not - even
though the docs say it should. i'm just using array_walk to benchmark
data-retrieval in a custom db class...rather than using a foreach on the
records returned, i'd be trying to walk the records - goal being to
standardize access methods, i.e. $records[0]['FOO'] as the structure...a row
and field as keys. the foreach is pretty fast over 200K rows...just wanna
see how much faster the native iteration is over the native enumeration. :)
i'm just wierd like that.

anyway, the code i posted here was me just playing with array_walk in a
practical scenario. just trying to find out about what all i could do with
the userdata param. that's when i ran into this bit of undefined behavior.
and, isn't it wonderful that it is undefined yet a single character's
correction would fix the problem - that character being '&' as a call-time
by-reference.

thanks for the help.


Yeah, glad to help.. It also challenges my mind not to be complacent.

Hendri
Apr 20 '07 #7
| Also forgot to mention that posted code also doesn't work.
| (You might have found a bug?? :D )

well, if it is consistent then it's a 'feature', right? lol.

btw, i ran it on php 5.1.6.
Apr 20 '07 #8
On 20.04.2007 05:57 Steve wrote:
here's a quirk i can't seem to handle, just hack. since call-time
by-reference is depreciated and i don't want to enable it in the php.ini,
i'm kind of stuck when i want to pass userdata as an array byref that is
initially = array().

// the array being walked
$numbers = array(1, 56, 999, 1000, 28, 65);

// the work-around

// the callback
function validateInput(& $value, $key, &$errors)
{
$maxValue = 999;
if ($value <= $maxValue) return;
$errors[1][$key] = 'Element ' . $key. ' must be a whole number between 0
and ' . $maxValue . '.';
}
// the hack
$error = array();
$errors = array('', &$error);
array_walk($num bers, 'validateInput' , $errors);
$errors = $errors[1];
print_r($errors );

// what i'd like to do

// the callback
function validateInput(& $value, $key, &$errors)
{
$maxValue = 999;
if ($value <= $maxValue) return;
$errors[$key] = 'Element ' . $key. ' must be a whole number between 0 and
' . $maxValue . '.';
}
$errors = array();
array_walk($num bers, 'validateInput' , $errors);
print_r($errors );
it seems as though php doesn't allocate memory for $errors when it is
defined as an empty array since it has no data (!isset), and therefore
there's a pointer to nothing (figuratively). i assume since $errors =
array('', &$error) allocates memory for the structure, the callback then has
something to work on. the '' being what actually triggers allocation (makes
room for \0 i guess). that was my reasoning when i came up with the hack,
but i'd like to know for sure.

does that sound about right? suggestions on getting the results i looking
for?

tia,

me
Hi

how about

function validateInput(& $value, $key, $errs)
{
$maxValue = 999;
if ($value <= $maxValue) return;
$errs[0][$key] = "message... ";
}

array_walk($num bers, 'validateInput' , array(&$errors) );
print_r($errors );


--
gosha bine

extended php parser ~ http://code.google.com/p/pihipi
blok ~ http://www.tagarga.com/blok
Apr 20 '07 #9
| function validateInput(& $value, $key, $errs)
| {
| $maxValue = 999;
| if ($value <= $maxValue) return;
| $errs[0][$key] = "message... ";
| }
|
| array_walk($num bers, 'validateInput' , array(&$errors) );
| print_r($errors );

beautiful...i check it. i wonder why it has to be that way instead of just
passing $errors in?
Apr 20 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1967
by: Phil Powell | last post by:
<?php class Grad { var $dbFormExemptionArray = array(); function Grad ($id = '') { /*---------------------------------------------------------------------------------------------------------------------- Do note that if you are generating arrays that will not have
2
2961
by: Reply-Via-Newsgroup | last post by:
Folks, I have a multi-dimensional array that I read from my mysql database. I'd like to run strip slashes against each element and I'm pretty sure that array_walk() (or array_map) is likely to solve my problem - But I've not got the foggiest on how to use it - I've taken a look in the php.chm manual supplied from php.net and I don't seem to have had any success so far - Can anyone suggest how I could stripslashes to every element...
1
1822
by: comp.lang.php | last post by:
/** * Filter results according to given instruction * * @access private * @param object $result (reference) * @return object $filteredResult */ function &filterResults(&$result) { // STATIC OBJECT ARRAY METHOD global $section;
6
3052
by: steve | last post by:
Hi, I have never used array_walk, and quite frankly, cannot see why I should use it instead of foreach. Can someone shed some light on the cases where array_walk is the one to use, and what php developers where thinking when they coded this operator. Thanks. --
1
6374
by: e | last post by:
I'm using forms authentication on a site. When the user logs in via the login page, the entered creds are checked against AD, and if valid, an encrypted forms authentication ticket is produced and stored in the forms auth cookie (and written to the client), using this code: ____________________ 'create the forms auth ticket objAuthTicket = New FormsAuthenticationTicket(1, txtUsername.Text, _ DateTime.Now, DateTime.Now.AddMinutes(8),...
3
3692
by: Mr.KisS | last post by:
Hello all, I'm working with : WinXP PRO SP1, MS SQL 2005 Express, Visual Web Dev 2005 Express. I have an aspx page which must execute a stored procedure : ______________ try { myCommand.ExecuteNonQuery();
0
1517
by: Sean Patterson | last post by:
Hey all, I've followed the examples online on how to use Forms Authentication to create a ticket, assign it a role, and then intercept it in the Global.asax file to make sure it gets sucked in to the IPrincipal. This has worked on some other apps, but my code isn't working in my new one for some reason. Here's my CreateCredentials code: Private Sub CreateCredentials(ByVal UserID As String, ByVal UserRole As String)
2
2177
by: lwoods | last post by:
I have the following function: function clean_form( &$from_check ) { if(is_array($from_check)){ array_walk(&$from_check,'clean_form'); return; } else { $value = str_replace(array("\r","\n","Content-Type:"),"",$from_check); }
0
1010
code green
by: code green | last post by:
Using the third parameter to pass the address of a user array to array_walk fills the user array with data. But once array_walk finishes executing the user array empties. Can any body explain this? $assocPriceLists = array(); //Create price lists lookup table if(array_walk($priceLists, 'createAssoc', $assocPriceLists)) { print_r($assocPriceLists); //Prints Array(). assocPriceLists is empty function...
0
9698
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9556
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10292
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10052
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7589
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5616
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4156
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2959
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.