仅在php

时间:2016-02-05 13:51:55

标签: php arrays

如果有一个阵列:

$arr = array('o', 'v', 'e', 'r','f', 'l', 'o', 'w');

我希望在php中使用仅循环来显示1st string = revo2nd string = flow的输出。不使用任何内置的php函数

那我怎么办呢?请帮帮我。

2 个答案:

答案 0 :(得分:0)

解决方案是:

$arr = array('o', 'v', 'e', 'r','f', 'l', 'o', 'w');
            |_________________| |_________________|
                     ^                    ^
             Reverse this half  Keep this half as it is

然后遍历数组以创建第一个和第二个字符串。

$arr = array('o', 'v', 'e', 'r','f', 'l', 'o', 'w');

// Reverse the first half of the array
$arrLength = count($arr);
for($i = 0; $i < $arrLength / 4; ++$i){
    $tmp = $arr[$i];
    $arr[$i] = $arr[(($arrLength / 2) - 1) - $i];
    $arr[(($arrLength / 2)  - 1) - $i] = $tmp;
}

// Loop through the array to create first and second string
$firstString = $secondString = "";
for($i = 0; $i < $arrLength; ++$i){
    if($i < $arrLength / 2){
        $firstString .= $arr[$i];
    }else{
        $secondString .= $arr[$i];  
    }
}

echo "First String: " . $firstString . "<br />";
echo "Second String: " . $secondString . "<br />";

输出:

First String: revo
Second String: flow

答案 1 :(得分:0)

尝试这个..

     <?php
     $arr = array('o', 'v', 'e', 'r','f', 'l', 'o', 'w');
     $str1='';
     $str2 ='';
     //where we gave for loop length as 8(arr length)
     for($i = 0; $i <8; $i++) {

        if($i<4){ //which is used to reverse the first half string 

            $j =3;

            $str1.=$arr[$j-$i];
            //where we reverse the order as 3,2,1,0.and concat the each char as string.
        }else{
            $str2 .= $arr[$i];
       //rest char is simply passed as string 2
        }  
    }

    echo $str1."</br>";
    echo $str2;
    ?>