Echo printf and printf in php

Русские Блоги

Выход в PHP: echo, print, printf, sprintf, print_r и var_dump

Каждый часто будет просить в интервью:

Пожалуйста, кратко объясните, что такое метод печати PHP?

Пожалуйста, объясните разницу между Echo, Print, Print_r.

Это очень просто, как правило, в младшем ростом письменном вопросе. Но чтобы по-настоящему понять, что эти языковые структуры или функции не так просто. Сегодня давайте посмотрим на эти распечатки, связанные со содержанием.

echo

Наиболее базовым выходом, а не функция является языковой структурой и не требует скобок. Вы можете использовать список параметров для разделения запятой. Но если вы добавите скобки, вы не можете использовать запятую для разделения вывода. Там нет возвращаемого значения.

echo 'fullstackpm'; // Нормальный выход: fullstackpm echo 'fullstackpm', ' is ', 'Good!'; // Нормальный вывод: fullstackpm хорош! echo ('fullstackpm'); // Нормальный выход: fullstackpm echo ('fullstackpm', ' is ', 'Good!'); // Сообщить об ошибке Копировать код

print

В основном, как echo, но не поддерживает список параметров, есть возвращаемое значение. Возвращаемое значение всегда 1.

Потому что есть возвращаемое значение, это не так хорошо, как эхо.

print 'fullstackpm'; // Нормальный выход: fullstackpm print 'fullstackpm', ' is ', 'Good!'; // Ошибка $r = print ('fullstackpm'); // Нормальный выход: fullstackpm print $r; // вывод 1. Копировать код

Printf и sprintf.

Две высоко высокие функции могут отформатировать выходную строку. С% указывают на заполнитель, параметры задней части соответствуют замене заполнителя. Разница между PrintF и SPRINTF заключается в том, что первый напрямую выводится, а последняя функция строки обратно. Пожалуйста, смотрите пример.

$str = 'My name is %s, I\'m %d years old.'; printf($str, 'fullstackpm', 1002); // Прямой вывод: меня зовут fullstackpm, мне 1002 года. $s = sprintf($str, 'WoW', 12); / / Не будет выведен здесь print $s; // вывод: меня зовут вау, мне 12 лет. Копировать код

Вы меньше всего помните,% s представляет строку,% d представляет число,% f — это номер с плавающей запятой, %% — это сам вывод, а также есть много типов для просмотра соответствующих документов. Есть также несколько похожих:

  • VPrintf, его второй параметр — это массив, а не параметр переменной длины.
  • SSCanf отличается от некоторых специальных персонажей.
  • Fscanf, прочитайте и отформатируйте его из документа.

Очень часто используемая функция, которая может отформатировать выходной массив или объект. Обратите внимание, что второй параметр установлен на true, и он может быть выведен без прямого вывода, но функция возвращается.

$str = [ "a", 1 => "b", "3" => "c", "show"=>'d' ]; print_r($str) // вывод /** Array ( [0] => a [1] => b [3] => c [show] => d ) */ $s = print_r($str, true); // не выводится echo $s; // вывод // Обратите внимание, что выходной поток не находится в Ob_Start (), не имейте никаких других выходов в этом абзаце. /** Array ( [0] => a [1] => b [3] => c [show] => d ) */ Копировать код

Var_dump и var_exports.

VAR_Dump также является очень распространенной функцией для отображения информации о структуре, включая типы и значения, объекты массива и отступ указывают иерархическую. Var_exports и разные места заключаются в том, что контент, возвращаемый var_exports, — это обычный код PHP, который можно использовать непосредственно, и есть второй параметр возврата, аналогичный pept_r, эффект аналогичен.

$str = [ "a", 1 => "b", "3" => "c", "show"=>'d' ]; var_dump($str); // вывод /** array(4) < [0] =>string(1) "a" [1] => string(1) "b" [3] => string(1) "c" 'show' => string(1) "d" > */ var_export($str); // вывод /** array ( 0 => 'a', 1 => 'b', 3 => 'c', 'show' => 'd', ) */ Копировать код

Перепечатано на: https: //juejin.im/post/5c887683f265da2d9e1794d4

Источник

What’s the difference between echo and printf

Solution 4: echo — Output one or more strings echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. There are probably differences in performance between , and , but I wouldn’t get too hung up on them since in a database driven web application (PHP’s typical domain), printing strings to the client is almost certainly not your bottleneck.

What’s the difference between echo and printf

What’s the difference between echo and printf?

The main difference is that printf receives first a format string, with placeholders (those % signs you see), and can even accept some formatting parameters (like %2d, which would show 2 digits for a number).

Echo is, instead, just displaying the string. When you do «$i bar», the string is first expanded with the value of $i, and then sent to the echo function to be shown.

If you search the differences in any search engines, you’ll get your answer. For example below is one use for printf:

You can use this function to format the decimal places in a number:

$num = 2.12; printf("%.1f",$num); prints: 2.1 

And of course this is only just one use. Another good sample that i use is below:

If you are printing data in a «pre» tag, courier font, or otherwise non-variable length font (like a terminal), you might have use for printf’s justify feature.

$value1 = "31298"; $value2 = "98"; print "
\n"; printf ("%'.-15.15s%'.6.6s\n", $heading1, $value1); printf ("%'.-15.15s%'.6.6s\n", $heading2, $value2); print "

\n"; ?>
Php — What’s the difference between echo and printf, The main difference is that printf receives first a format string, with placeholders (those % signs you see), and can even accept some formatting parameters (like %2d, which would show 2 digits for a number). Echo is, instead, just displaying the string. Code sample$value2 = «98»;print «

\n";printf ("%'.-15.15s%'.6.6s\n", $heading1, $value1);printf ("%'.-15.15s%'.6.6s\n", $heading2, $value2);print "

\n»;Feedback

Php : echo»», print(), printf()

Is there a better way to output data to html page with PHP?

If I like to make a div with some var in php, I will write something like that

What is the proper way to do that?

Or a better way, fill a $tempvar and print it once? like that:

$tempvar = '
'.$var.'
' print ($tempvar);

In fact, in real life, the var will be fill with much more!

There are 2 differences between echo and print in PHP:

  • print returns a value. It always returns 1.
  • echo can take a comma delimited list of arguments to output.

Always returning 1 doesn’t seem particularly useful. And a comma delimited list of arguments can be simulated with multiple calls or string concatenation. So the choice between echo and print pretty much comes down to style. Most PHP code that I’ve seen uses echo .

printf() is a direct analog of c’s printf() . If you’re comfortable in the c idiom, you might use printf() . A lot of people in the younger generation though, find printf() ‘s special character syntax to be less readable than the equivalent echo code.

There are probably differences in performance between echo , print and printf , but I wouldn’t get too hung up on them since in a database driven web application (PHP’s typical domain), printing strings to the client is almost certainly not your bottleneck. The bottom line is that any of the 3 will get the job done and one is not better than another. It’s just a matter of style.

$var = "hello"; echo "Some Text $var some other text"; // output: // Some Text hello some other text 
print("Some Text $var some other text"); // output: // Some Text hello some other text 

doesn’t make big difference. This works with double-quotes only. With single quotes it doesn’t. example:

$var = "hello"; echo 'Some Text $var some other text'; // Note the single quotes! // output: // Some Text $var some other text 
print('Some Text $var some other text'); // Note the single quotes! // output: // Some Text $var some other text 

Just try this you gonna love the well formated amount of infos :

OK, I explain : set a «code» html format and var_dump show the value, the type, the params . of the variable.

Or if you don’t have short tags on, you might need to

if you have the short_open_tag option enabled you can do

Syntax — php : echo»», print(), printf(), There are 2 differences between echo and print in PHP: print returns a value. It always returns 1. echo can take a comma delimited list of arguments to …

Printf() is less reliable than echo in PHP?

For some reason, I have adopted using printf($var) over using echo $var . I don’t really know why.

However, it seems like if I ever have an issue outputting a string from a variable — if I change printf($var) to echo $var — 90% of the time it fixes the issue.

This has happened to me on more than one occasion with differing errors, anywhere from too few arguments to just echoing a null/blank string.

Can anyone shed some light as to why printf() seems to work less reliably than echo ?

Short answer, don’t use printf($var) unless you specifically need it.

The reason is that $var passed as the first argument is treated as a format string and things like %s and %d , etc. have a special meaning . In C / C++ this can cause segmentation faults, whereas in PHP you get a slap on the wrist in comparison.

The equivalent of echo or print is printf(‘%s’, $var) ; it casts $var to a string and then outputs it.

Btw, printf() is a function whereas echo and print are language constructs; therefore you’re likely to get better performance with echo .

printf — Output a formatted string ,print returns a value. It always returns 1.and what the echo do — Output one or more strings

Always returning 1 doesn’t seem useful. And a comma delimited list of arguments can be simulated with string concatenation or multiple calls

The print function is slightly more dynamic than the echo function by returning a value, and the echo function is slightly (very slightly) faster. The printf function inserts dynamic variables/whatever into wherever you want with special delimiters, such as %s , or %d . For example, printf(‘There is a difference between %s and %s’, ‘good’, ‘evil’) would return ‘There is a difference between good and evil’ .

check this PHP: Benchmarking echo vs. print vs. printf

it appears that echo and print are really, really close in terms of speed. The difference per command was only 2/1,000,000 of a second. It just comes down to personal preference. I use echo because that’s what I used first. The speed drop on print appears to come when you assign a variable, at which point the command speed drops 1/100,000 of a second, which is still fairly minor.

printf is very different from using echo , first of all printf is a function returning a value while echo is what is normally referred to as a » language construct «.

The first argument to printf is supposed to be a format-string which is, exactly as the name implies, used to format the outputted string.

echo will output the » parameters » passed to it as they are (after variable interpolation that is), while printf will behave according to the first format-string , as mentioned earlier.

For example, try the below snippet and notice some major differences.

echo "I like %s! hello ", "world", " /stackoverflow" ; echo "\n" printf ("I like %s! hello ", "world", " /stackoverflow"); 
I like %s! hello world /stackoverflow I like world! hello 

written and edited using my BlackBerry , sorry for any formatting errors..

echo — Output one or more strings

echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses.

printf — Output a formatted string

Returns the length of the outputted string

Printf() is less reliable than echo in PHP?, 3. printf is very different from using echo, first of all printf is a function returning a value while echo is what is normally referred to as a » …

Источник

Читайте также:  Php удаление символов переноса строк
Оцените статью