Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I have an array, I want to check fo 1

Status
Not open for further replies.

SurfScape

Programmer
Joined
Nov 6, 2003
Messages
6
Location
US
I have an array, I want to check for errors before placing in my db.

Code:
[data] => Array
        (
            [E001] => 40.00
            [E021] => 2.25
            [E022] => 1.16
            [E01S] => 0.00
            [E012] => 0.00
            [E09B] => 0.00
        )

Now, these values can only have possible values of x.25, x.50, x.75 , x.00 or x. so I want to do a foreach loop through the array and determine if any of these values doesn't meet that criteria.

I've tried several different approaches including:

Code:
    foreach( $_POST['data'] as $k => $v ) {
      if ( ($v % .25) > 0 )  {
        $site->raise_error( 'All data must be either .25, .50, .75, .00' );
      }
    }
Which didn't work, well I don't know why, maybe because the values are strings? also the modulus (%) doesn't seem to work with decimals.

I also tried:
Code:
    foreach( $_POST['data'] as $k => $v ) {
      $v = $v / .25;
      if ( is_double($v)  )  {
        $site->raise_error( 'All data must be either .25, .50, .75, .00' );
      }
    }

Which didn't work either, I think because a division operator automatically makes it a double or float.

If anyone can clue me in, I'd appreciate it.

-Garrett:confused:
 
You could do it by stripping out a substring and then forcing PHP to do an implicit cast:

foreach ($_POST['data'] as $v)
{
$decimals = substr($v, -2);

if (($decimals % 25) != 0)
{
$site->raise_error( 'All data must be either .25, .50, .75, .00' );
}
}



Want the best answers? Ask the best questions: TANSTAAFL!!
 
Thanks that worked like a charm, I had to format the data, the array I showed was after the data was reposted to the form for another error. Values could be 40 and Null so, here it is. Much Thanks again.

Code:
   foreach ($_POST['data'] as $v)
     {
         $v =  sprintf( "%01.2f", $v );
         $decimals = substr($v, -2);
         if (($decimals % 25) != 0)  {
             $site->raise_error( 'All data must be either .25, .50, .75, .00.<br> See the rounding charts!' );
         }
     }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top