自定义函数实现字符串数组互转

清风徐来水波不兴 2019-12-30

自定义函数 实现字符串转数组

<?php
$str = ‘I want to go home ‘;
strToArr( $str );
function strToArr( $str )
{
    $arr = [];
    $s = ‘‘;
    for ( $i=0; $i < strlen( $str ); $i++) { 
        if( $str[$i] == ‘ ‘ )
        {
            $arr[] = $s;
            $s = ‘‘;
        }
        else
        {
            $s.= $str[$i];
        }
    }
    if( $s != ‘‘ && $s != ‘ ‘ )
    {
        $arr[] = $s;
    }
    return $arr; 
}
?>

自定义函数 实现数组转字符串

<?php
$arr = [‘I‘, ‘want‘, ‘to‘, ‘go‘,‘home‘];
echo arrToStr( $arr );
function arrToStr( $arr )
{
    $str = ‘‘;
    foreach ($arr as $key => $value) {
        if( $key == 0 )
        {
            $str = $value;
        }
        else
        {
            $str .= ‘ ‘.$value;
        }
    }
    return $str;
}
?>

相关推荐