• PHP输出函数print, printf, sprintf的区别


    PHP中常用的字符串输出方式是:使用echo和print两种方法来显示字符串。如果涉及格式化输出操作,还可以试用printf和sprintf函数。

    一、先说echo和print两种方法

    1. print的语法格式为:int print ( string $arg   )  
    2. echo的语法格式为:void echo ( string $arg1   [, string $...  ] )

    echo都是一种类似于函数的输出方式而非函数,没有返回值,且支持多参数;

    print是输出函数,其返回值为int类型的1,且只支持一个参数。

    echo用法即可以用英文逗号","连接多参数,也可以用英文点号"."作为连符组成一个参数,举个栗子:

    echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
    echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "
    ";

    print就不能用上面的英文逗号","连接多参数,只能用英文点号"."作为连符组成一个参数。例如上述第二句用print写法为:

    print('This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "
    ");

    二、重点来了,PHP中sprintf和printf函数都是用来格式化操作字符串的,两者的输出语法格式分别为:

    1. printf的语法格式为:int printf    ( string $format   [, mixed $args   [, mixed $...  ]] )
    2. sprintf的语法格式为:string sprintf    ( string $format   [, mixed $args   [, mixed $...  ]] )

    两者的区别是:

    1. printf()函数可以直接将格式化之后的字符串输出,而sprintf()函数需要使用echo方法将格式化后的字符串输出。
    2. printf()函数的返回值为int类型,表示打印出来字符串的字符数量,而sprintf()函数的返回值为一个字符串。

    举个例子就都明白了:

    <h3>PHP输出函数print,printf,sprintf的区别</h3>  
    <?PHP 
    $str='This is an example for this.'; 
    echo $str."<br>";     //这里输出This is an example for this.
    $number=print ($str."<br>");    //这里输出This is an example for this.
    echo $number."<br>";  //这里输出1
    $format="%b, %c, %d, %s"; 
    $num1=printf($format,65,65,65,65);   //这里输出1000001, A, 65, 65
    echo "<br>";
    echo $num1."<br>";  //这里输出18,对应字符串的个数
    echo sprintf($format,97,97,97,97);  //这里利用echo输出1100001, a, 97, 97
    ?>
  • 相关阅读:
    转载:一句代码改变Swing难看的字体
    生产者消费者问题c语言实现
    水题~~~~HDU 4788
    html中dom居中的5种方式
    scss中的三角函数
    nuxt基础Ⅱ
    nuxt基础Ⅰ
    win10软件安装出现错误代码2503/2502
    npm淘宝镜像安装
    axios的使用
  • 原文地址:https://www.cnblogs.com/whiterock/p/7280345.html
Copyright © 2020-2023  润新知