SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Wizard
    Join Date
    Dec 2004
    Location
    USA
    Posts
    1,407
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    how can youy cast an entire array to (int)? $_POST array

    I have an array coming in $_POST variables and need to multiply each number in the array. See code:

    $a = $_POST['weight'];
    $ct = count($a)-1;
    for ($i = 0; $i <= $ct; $i++) {
    print $_POST['weight'][$i]*3."<BR>";
    }

    I need to cast each element in the array to INT before multiplying since it comes in as string.

    Is there an short way to cast the entire array or how would I do this for each element?

    Thanks!

  2. #2
    SitePoint Wizard silver trophy someonewhois's Avatar
    Join Date
    Jan 2002
    Location
    Canada
    Posts
    6,364
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is PHP - no type casting required.

    $a = '5';
    echo $a * 3;

    Will output 15, despite it being a string.

    You can also use this:
    foreach($_POST['weight'] AS $k=>$v)
    {
    echo $v * 3;
    }

    Instead of doing that for loop. Handy for arrays.

  3. #3
    SitePoint Zealot
    Join Date
    Nov 2004
    Location
    San Diego, CA (USA)
    Posts
    126
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    $array $_POST['weight'];
    foreach (
    $array as $item) {
        
    $item $item*3;
        print 
    $item.'<BR>';

    that should work, if i understood you correctly...

  4. #4
    SitePoint Wizard swdev's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    1,053
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Another way of doing this is

    PHP Code:
      $weight $_POST['weight'];
      
      function 
    alter_array(& $item$key$multiplier)
      {
        
    $item  *= $multiplier;
      }
      
      
      
    array_walk($arr'alter_array'3); 
    array_walk click on the link to see the manual definition for array_walk.

    hope this helps

  5. #5
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yet another way:

    PHP Code:
    $a = array(123);
    $b preg_replace("~\d+~e""$0*3"$a);
    print_r($b); 

  6. #6
    SitePoint Wizard
    Join Date
    Dec 2004
    Location
    USA
    Posts
    1,407
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    got it working - thanks guys


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •