Home php教程 php手册 常用PHP变量输出:echo, prinf, sprintf, var_dump

常用PHP变量输出:echo, prinf, sprintf, var_dump

Jun 06, 2016 am 09:54 AM
dump echo php var code variable Open source programming programming language software development output

1、使用 echo 语句
      使用 echo  可以打印变量和内容,其他可以是系统变量,也可以是HTML代码,也可以是一个PHP表达式,如下示例:
               $a = "12345";    //  变量赋值
               $b = "this is string";
               // 下面分别打印显示两个变量内容
              echo $a ;
              echo $b;
              // 显示由表单提交的内容
              echo $_POST['UserName'];
              $str1 = "FREEBSD";
              $str2 = "PHP";   //HTML式文本
              // 链接字符串$str1和$str2并显示
              echo $str1."and".$str2."is good partners." ;
      ?>
 
2、使用printf函数
      printf函数用于格式化输出字符串,主要用于字符串中以%开头的格式字符串替换。
      语法: boolean printf ( string format[,mixed args] )
      请看下面的例子:
                   printf ( "$%01.2f", 43.2) ;  //  运行结果 : $43.20
                   printf ( "%d bottles of beer on %s", 100 , "the wall" ) ;
                   // 运行结果: 100 bottles of beer on the wall
                   printf ( "%15s", "some text" ) ;  // 运行结果:  some text
      ?>
 
      可以看到,以%开头的格式字符串,则按顺序进行参数替换显示。如下所示:
                  printf ( "The %2\$s likes to %l\$s", "bark", "dog" ) ;
                  // 运行结果: The dog likes to bark
                  printf ( "The %l\$s says: %2\$s , %2\$s.","dog", "bark" ) ;
                  // 运行结果: The dog says : bark ,  bar.
 
3、使用sprintf 函数
      sprintf 函数也用做字符串格式化。该函数与 printf 函数基本相同, 但它可以将转换后的结果保存到一个字符串变量中,而不是直接输出。
      语法: string sprintf ( string format , mixed [args]... ) ;
      其中参数 format 是转换的格式,以百分比符号%开始到转换字符为止。请见下面的脚本例子:
                      $var1 = 68.75 ;
                      $var2 = 54.35 ;
                      $var3 = $var1 + $var2 ;
                      // 变量$var3值为"123.1";
                      $formatted = sprintf ( "%01.2f ", $var3 ) ;
                      // 变量 $var3 值为"123.10"
      ?>
      其中:%01.2f 的%符号是指定格式的开始,也就是从“起始字符”开始,直到出现“转换字符”,格式化字符的工作正式结束。
      在%
符号后面的0表示“填空字符”,如果位置为空就用0来填充,在0后面1规定小数点的前面的数字占位要有1位以上,把1换成2,若$var3的值为
1.23,则$formatted的值将为01.23。由于在小数点前面的数字只占了一位,按照上面所规定的格式,小数点前面数字应该占2位,现在只有1
位,所以用0来填满。在%01后面的 .2 的意思是规定小数点后的数字,必须占2位。如果$money的值为1.234,则$formatted
的值将为1.23。为什么4不见了呢?因为在小数点后面按照上面的规定,必须且仅能占2位。可是$var3的值中小数点占了3位,所以4被去掉了,只剩下
23 。
        最后,以f 转换字符结尾,其他转换字符请参考下面的字符转换列表。
 
 转换字符  功能说明
 %  打印出百分比符号,不转换
 B  整数转成二进制数
 C  整数转成ASCII字符
 D  整数转成十进制
 F  倍精度数字转成浮点数
 O  整数转成八进制数
 S  整数转成字符串
 x/X  整数转成小写/大写的十六进制数

 
        如果在%起始符号后面加上 - (负号)则会把数字按右对齐的方式进行处理。如下例所示。
                             $money = 1.4 ;
                     $formatted = sprintf ( "%-02.2f", $money ) ;
                     echo $formatted ;
        ?>
        这时候,$formatted 将不会再是01.40而是1.400
        转换的格式一次包括如下:
        1、填空字符。0的话表示空格填0;空格是默认值。
        2、对齐方式。默认值为向右对齐,负号表示向左对齐。
        3、字段宽度。为最小宽度。
        4、精确度。指在小数点后的浮点位数。
 
4、  关于echo 与 print语句的区别
        echo是一个语句,单纯显示文本信息或变量值,而却没有返回值;
        printf (包括printf、sprintf )则是一个函数,可以返回一个布尔值(True 或 False);
        echo 语句没有返回值,但是可以使用 .  (小圆点)来拼接字符串,而print则不可以。如果单纯做显示,使用     echo的效率会高一些(无返回值)。

5.var_dump
打印变量的相关信息,

此函数显示关于一个或多个表达式的结构信息,包括表达式的类型与值。数组将递归展开值,通过缩进显示其结构。
// 字符串变量
$a = "123";
var_dump($a);
运行结果:string(3) "123"
打印出该变量的:类型,长度,value值;


// 数值型数量
$b = 456;
var_dump($b);
运行结果:int(456)
打印出该变量的:类型,value值;


// 数组
$c = array('PHP起点', 'phpqidian.com');
var_dump($c);
运行结果:array(2) {
  [0]=>
  string(9) "PHP璧风偣"
  [1]=>
  string(13) "phpqidian.com"
}
打印出该数组的:类型,元素数,及元素对应的信息;


// 布尔类型变量
$d = true;
var_dump($d);
运行结果:bool(true)
 
PHP小班培训 | PHP视频教程 | PHP培训
天通苑PHP培训
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles