简体   繁体   中英

Why my loop only work to the half of the table ? I have no idea

I want to write a program, that will make 2 arrays (one with integers and second with strings) from one array (mixed strings and integers. I have problem with my loop for i guess, becaouse it seems that it works only to the half of the table.

function check(&$tab,&$tabstr,&$tabint){
    for($i=0;$i<count($tab);$i++){
        if(is_numeric($tab[$i])==1){
                $tabint[]=$tab[$i];
                unset($tab[$i]);
        }else
                $tabstr[]=$tab[$i];
                 unset($tab[$i]);
    }
}

I believe you shouldn't unset($tab[i]) in the loop, I would unset $tab after the loop has finished. It might be messing up the positions and your value. Also I think the else is not opening and closing {} properly.

I'll do like this:

function check(&$tab,&$tabstr,&$tabint) {
    $tabint= array();
    $tabstr= array();
    for($i=0;$i<count($tab);$i++) {
        if(is_numeric($tab[$i])==1) {
           array_push($tabint, $tab[$i]);
        }
        else {
           array_push($tabstr, $tab[$i]);    
        }
    }
    unset($tab);
}

Here While unset the $tab variable, the count($tab) value would change so the loop will brake. So assign the count of $tab to variable then check, here is a code

function check(&$tab,&$tabstr,&$tabint){
    $length = count($tab);
    for($i=0;$i<$length;$i++){
        if(is_numeric($tab[$i])==1){
                $tabint[]=$tab[$i];
                unset($tab[$i]);
        }else{
                $tabstr[]=$tab[$i];
                 unset($tab[$i]);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM