SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    Always A Novice bronze trophy
    K. Wolfe's Avatar
    Join Date
    Nov 2003
    Location
    Columbus, OH
    Posts
    2,180
    Mentioned
    65 Post(s)
    Tagged
    2 Thread(s)

    Array_filter() with pregmtach

    End of the day and I'm struggling:

    Code PHP:
    <?php
    $arr1 = array(
            "6263888445",
            "3134003757",
            "985415628" // should be moved to another array
    );
     
    $arr2 = array();
     
    //preg_match('/^[0-9]{10}$/'), $var);

    I want to use that reg ex to move anything that fails to $arr2

  2. #2
    Always A Novice bronze trophy
    K. Wolfe's Avatar
    Join Date
    Nov 2003
    Location
    Columbus, OH
    Posts
    2,180
    Mentioned
    65 Post(s)
    Tagged
    2 Thread(s)
    Yeah, so the title says where I was going wrong. I'll just run a foreach and do the check, unless of course someone can think of something cooler?

  3. #3
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    How about you sort the array, and anything less than 1000000000 or strlen === 10 you move to the other array?

    PHP Code:
    $arr1 = array(

            
    "6263888445",
            
    "3134003757",
            
    "100",
            
    "985415628""1",
    );

    $arr2 = array();
    sort($arr1);

    foreach( 
    $arr1 as $k => $a){
    if ( 
    strlen($a) < 10  ){
    $arr2[] = $a ;
    unset(
    $arr1[$k]);
    }
    if(
    strlen($a) === 10) continue ;  // drop out of the loop as soon as a 10 figure amt is found
    }

    var_dump($arr1);
    var_dump($arr2); 

    array
    3 => string '3134003757' (length=10)
    4 => string '6263888445' (length=10)
    array
    0 => string '1' (length=1)
    1 => string '100' (length=3)
    2 => string '985415628' (length=9)

    EDIT
    This way you avoid having to run a regex in a loop, and you only perform the check on the top part of the sorted array, when it discovers a 10 char figure it quits.
    Last edited by Cups; Jan 6, 2013 at 05:26. Reason: added comments


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
  •