Showing posts with label PHP echo. Show all posts
Showing posts with label PHP echo. Show all posts

Monday, 5 August 2019

PHP echo construct

Today I had learned about PHP echo construct it is not a function , it is a language construct. By language construct I mean that meaning that it is an integral part of PHP itself. It allows us to output data on the users web browser. You can output values stored in a variable using echo or you can also output string data using echo. We can use both single quotation mark ‘ ‘ or double quotation mark ” “ while using echo. Double quotation mark are used when you want to output value of some variable to the browser in a program and your line must terminate with the semi colon ;

<?php
echo "!I am echo construct!";
?>
view rawecho-in-php1 hosted with ❤ by GitHub
Now this would output !I am echo construct! to the web browser. Now the semi-colan (;) at the end of the echo command is used to mention the end of the echo construct. Without this semi-colon PHP would report an error.
So previous example shows the use of echo with double quotation marks. As stated earlier we can also use it with single quotation marks as shown below
<?php
echo '!I am echo construct!';
?>
view rawecho-in-php2 hosted with ❤ by GitHub

Now this would also output !I am echo construct! to the web browser.
In PHP we can also use echo to do arithmetic as can be seen in following example
<?php
echo 20+20;
echo '20+20';
?>
view rawecho-in-php3 hosted with ❤ by GitHub

Here line 2 is
echo 20+20;
This would output 40. This means echo command can be used for doing arithmetic and here note that quotation marks have not been used. You can also subtract , do division and multiplication using this echo construct.
Here line 3 is
echo ’20+20′;
This would literally output 20+20. This happens because quotation marks were used, this was processed as a string instead of a mathematical operation. And same thing would happen if we use double quotation marks instead of single quotation marks.

PHP tutorial: Constant and echo-print statement

Constant  and echo-print statement

Constants:
1) A constant is a name or an identifier for a simple value. It is defined using the define function and it does not start with $ sign
define(“DBNAME”, TECH);
2) A constant value cannot change during the execution of the script. By default, a constant is case-sensitive. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.
3) A constant differ from variable as variable value can be changed across the execution while constant value cannot
4) Constant value are global across the execution.
5) constant value are retrived using constant() function or simlying we can use echo
<?php
echo “DBNAME”;
echo “constant(DBNAME);
?>
6) PHP defined some predefined constants like _LINE_,_FILE_, _CLASS_
Print/echo statement
1) Print /echo does the same job i.e printing the statement on the screen
example
<?php
print “This is php script”;
echo ” This is php script”;
?>
2) It print the variable name in the same manner as given below
<?php
$x=10
print “This is $x”;
echo ” This is $x”;
?>
This is 10
This is 10
3) The behavior with single quotes is different
<?php
$x=10
print ‘This is $x’;
echo “This is $x”;
?>

Tuesday, 18 September 2018

PHP echo with commas versus concatenation

The language constructs "echo" and "print" are used in PHP for writing strings out to a stream, such as a web browser via a web server, or to the console when PHP is run as a command line script. The two work in a very similar way but for all intents and purposes are the same.
I have always used concatenation when writing out multiple strings with echo or print, but recently discovered that echo accepts multiple arguments or parameters, comma separated like a regular function call.
For example, when using concatenation, you would do this:
echo $string1 . $string2;
print $string1 . $string2;

When using commas with echo, you would do this:
echo $string1, $string2;
Note that you can only do this with echo and not with print; if you try to use comma separated values with print you will get a syntax error message.
Having learnt this, I decided to do some benchmarking to see if it is any faster using the comma variation or normal string concatenation, assuming the comma version would be slightly faster. In my tests, I first joined two 100 character strings four million times, and then three 100 character strings four million times. The reason for doing it so many times was to get large enough time values to make a meaningful comparison.
This survey was not particularly scientific: I ran each test a number of times and worked out a rough average in my head. However, the numbers produced were different enough in each iteration to clearly see that one method was faster than another.
Joining two 100 characters strings four million times:
echo $string1, $string2;
Approx average 1.48 seconds

echo $string1 . $string2;
Approx average 1.62 seconds

print $string1 . $string2;
Approx average 1.67 seconds
Joining three 100 characters strings four million times:
echo $string1, $string2, $string3;
Approx average 2.08 seconds

echo $string1 . $string2 . $string3;
Approx average 3.48 seconds

print $string1 . $string2 . $string3;
Approx average 3.52 seconds
So, as I expected, echo using commas is marginally faster than echo with concatenation, and echo with concatenation is marginally faster than print with concatenation. In the real world, the difference between the three would be infintisimal: it's only when we loop through thousands of times or more that we can see and measure any real difference.
Below is the benchmarking code I used to conduct this test. I needed to split it into an outer and inner loop with ob_get_clean() in the inner loop, otherwise the process would consume too much memory and error out. For example, the Apache log files said "PHP Fatal error: Allowed memory size of 16777216 bytes exhausted (tried to allocate 8396801 bytes)" when I tried to loop through too many iterations without cleaning the buffer. I could simply increase the allowable memory for the purposes of the test but having two loops was easy enough to do.
$string1 = str_repeat('x', 100);
$string2 = str_repeat('y', 100);
$string3 = str_repeat('z', 100);

$mark = microtime(true);

for($i = 0; $i < 2000; $i++) {
    
    ob_start();
    for($j = 0; $j < 2000; $j++) print $string1 . $string2 . $string3;
    ob_get_clean();

}

echo microtime(true) - $mark;

Friday, 31 August 2018

echo $ _GET ['id'] does not display anything

I have a page in which a user chooses a recipe which has a unique ID, they are then sent to another page where the information for that recipe is displayed but it is not displaying anything.

$recipes = mysql_query("
        SELECT DISTINCT `name`, `step1`, `step2`, `step3`, `image`, `reference`
        FROM `recipe` r
        INNER JOIN `recipe_ingredients` ri
        ON r.id = ri.recipe_id
        WHERE ri.ingredient_id IN (".$ingredient1.",".$ingredient2.",".$ingredient3.")
    ");

This is the query on the main page, this allows the user to choose a set of ingredients and then retrieve recipes from them.
echo '<form action="recipe.php?id=<?php echo $recipe_id;?>" method="POST">';
        echo '<input id="search" name="Look" type="Submit" value="Look" >';
        echo '</form>';

Under each recipe there is a button a user presses, this will send the user to the specific recipe.
$sql = mysql_query("SELECT `name`, `image`
FROM `recipe`
WHERE `id` = ".$_GET['id']." LIMIT 1");

This is the query I'm running on the results page (recipe.php)
Further down the page I ran this.
<?php
echo $_GET['id'];
?>

It didn't display an ID and in the url I was displayed with this:
"recipe.php?id="
There is data in the table so what am I doing wrong?

The following echo syntax is incorrect:
echo '<form action="recipe.php?id=<?php echo $recipe_id;?>" method="POST">';

should be:
echo '<form action="recipe.php?id='.$recipe_id.'" method="POST">';

I don't see where you are setting $recipe_id, which appears to be the root of your problem.
It is unclear where you are trying to retrieve the elusive $recipe_id from.
If your trying to pull it in from $recipes then you should include it in your sql statement:
SELECT `id`,....

then pull it in after your $recipes->fetch_assoc():
$recipe_id = $recipes['id'];

Monday, 2 February 2015

What's the difference between PHP echo() and PHP print()?

What's the difference between PHP echo() and PHP print()? 

<?php
     
print "Hello World! <br />";
     echo 
"Hello World! <br />";
     
// The above outputs the text "Hello World!" on two separate lines.
     // Notice they are identical in output!

     
print ("Hello World! <br />");
     echo (
"Hello World! <br />");
     
// The above are just the same, with parenthesis.
     // Notice both can act like functions, but note they actually aren't.
?>


In all actuality, Echo and Print differ based on how they are structured. Print returns a value much like a normal function would. But despite common belief, Print is not a function, as we can see by the fact that it doesn’t require parenthesis to work (Not to be confused with Printf). Print and Echo are actually both called language constructs, although this isn’t to say that we can’t make Print act like a function.

PHP Echo Vs Print: Which Is Faster?

Echo is faster than print. 

Print can be used as part of complex constructs, such as
($b) ? print “True” : print “False”; // or echo ($b ? “true” : “false”);
Also, if you want to use error output (@print”Test”;)
Print is easy because almost every language use it. but most php developers use echo because it is faster and it is sounds cool!

PHP Print and Echo both output data to the screen in a same pattern but PHP Echo and PHP Print differ based on how they are structured.

In PHP, echo is not a function but a language construct. In PHP, print is not a really function but a language construct. However, it behaves like a function in that it returns a value. 

The echo() function is slightly faster than print(). With echo you can send a string of text.
The print() function outputs one or more strings.