KEMBAR78
MCA Open Source-PHP Unit 1 and 2 | PDF | Php | Free Software
0% found this document useful (0 votes)
252 views24 pages

MCA Open Source-PHP Unit 1 and 2

Open source licensing is built on traditional legal foundations of copyright and contract law. An open source license is a contract that allows others to use and modify source code while protecting the original creator's rights through conditions like requiring attribution and sharing modifications publicly. There are permissive licenses that impose few conditions and copyleft licenses that require derivatives to also be shared openly. Popular open source licenses include the MIT, BSD, GPL and Apache licenses.

Uploaded by

akshbaskar16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
252 views24 pages

MCA Open Source-PHP Unit 1 and 2

Open source licensing is built on traditional legal foundations of copyright and contract law. An open source license is a contract that allows others to use and modify source code while protecting the original creator's rights through conditions like requiring attribution and sharing modifications publicly. There are permissive licenses that impose few conditions and copyleft licenses that require derivatives to also be shared openly. Popular open source licenses include the MIT, BSD, GPL and Apache licenses.

Uploaded by

akshbaskar16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Unit -1

Open Source Licensing: Basic Principles of Copyright Law


Open source licensing and development approaches have been challenging and
transforming software development for decades. Although open source licensing is often described
as radical, it is built on solid, traditional legal foundations, including the rights granted by
copyright under the law of the United States (and elsewhere), and the ways in which basic contract
principles can alter and supersede those rights.
Contract and Copyright
An open source license agreement is a contract that allows a party to utilize other people's
code in their applications. These agreements are essential because, without them, the U.S.
Copyright Act does not protect software and would allow anyone to use or redistribute it freely
and without permission from the copyright owner.
If someone were to develop an open source project and make it available on Github,
others could take their code and use it without permission from the author of that work. If this
were allowed, there would be no incentive for developers to create new projects since they
wouldn't get credit or recognition for their work; instead, another developer could just copy the
work and claim it as their own.
copyright is automatically attached to every novel expression of an idea, whether through
text, sounds, or imagery. Unlike copyright, a valid patent does not protect the expression of an idea
but the underlying substance of it. For example, a patent applicable to a microchip protects not the
expression of the chip itself, or the electrical diagram describing it, but the idea that given circuits
can be organized and made to operate in a particular way. Because of their potentially vast scope,
patents are construed more strictly, require a registration process, and last for shorter periods than
copyrights. This also applies to diary entries, letters, song lyrics, and drawings, even if they are
only done "off the cuff," in the most casual of circumstances. A copyright does not need to be
registered to be legally effective. As already noted, a copyright comes into force when the
protected work is created.
Open Source Software Licensing
An Open-Source license (OS license) is a license granted for a software and other
products which allow for the source code, blueprint or design of the said software to be used,
modified and/or shared under pre-defined terms and conditions. Usually, an OSS is released under
an OS license which serves as a legal agreement between the OSS author and the end-user. Open-
source licenses facilitate free and open-source software (FOSS) development. Intellectual property
(IP) laws restrict the modification and sharing of creative works. Free and open-source software
licenses use these existing legal structures for the inverse purpose of granting freedoms that
promote sharing and collaboration. They grant the recipient the rights to use the software, examine
the source code, modify it, and distribute the modifications. These licenses target computer
software where source code can be necessary to create modifications. They also cover situations
where there is no difference between the source code and the executable program distributed to
end users. Open-source licenses can cover hardware, infrastructure, drinks, books, and music.
There are two broad categories of open-source licenses,
Permissive and Copyleft.
Permissive licenses originate in academia. They grant the rights to modify and distribute with
certain conditions. These academic licenses usually require attribution to credit the original
authors and a disclaimer of warranty. Copyleft licenses have their origins in the free software
movement. Copyleft also requires attribution, disclaims warranties, and grants the rights to modify
and distribute. The difference is that copyleft demands reciprocity. Any derivative works must be
distributed with the source code under a copyleft license.
Popular open source licenses include the Apache License, the MIT License, the
GNU General Public License (GPL), the BSD Licenses, the GNU Lesser General Public License
(LGPL) and the Mozilla Public License (MPL).
Issues with Copyrights and Patents
Copyright is automatically attached to every novel expression of an idea, whether
through text, sounds, or imagery. Unlike copyright, a valid patent does not protect the expression
of an idea but the underlying substance of it. A patent gives the owner of the patent or a patentee,
the right to exclude others from making, using, and selling his/her invention thereby, giving an
absolute control over the use of his/her invention.
For example, a patent applicable to a microchip protects not the expression of the chip
itself, or the electrical diagram describing it, but the idea that given circuits can be organized and
made to operate in a particular way. Because of their potentially vast scope, patents are construed
more strictly, require a registration process, and last for shorter periods than copyrights.
Patent Rights and Open Source can be said to co-exist in two ways:
1. An author of an OSS may apply for a patent for that OSS.
2. An invention using an OSS modification may be included/specified in a Patent application.
When a patent is granted, it is the law that the owner of the patent can limit the use of its
invention. Patents are granted on a country-by-country basis. If the distribution and/or use of the
Software program are restricted in certain countries either by patents or by copyrighted interfaces,
the original copyright holder who places the Program under the OS License may add an explicit
geographical distribution limitation excluding those countries, so that distribution is permitted only
in or among countries not thus excluded.
Open source
Open source software is software with source code that anyone can inspect, modify, and enhance.
For example
o Linux operating system
o Apache web server application
o VCL media player
o Google Android
o LibreOffice
o Firefox browser
o WordPress
"Source code" is the part of software that most computer users don't ever see; it's the code
computer programmers can manipulate to change how a piece of software—a "program" or
"application"—works. Programmers who have access to a computer program's source code can
improve that program by adding features to it or fixing parts that don't always work correctly.
What is the use of open source software
 Reduced Costs
• Total Cost of Ownership (TCO)
• Development costs
• Support costs
• No per user/per instance costs
• Interoperability using open standards and APIs
• Can evaluate for suitability, security, etc.
• Can modify to address user‗s needs
• Avoid vendor or integrator lock-in
• Ability to do rapid prototyping/proof of concept
• Can share and redistribute with other organizations.

Benefits of Free and Open Source software(FOSS)


Besides the low cost of FOSS, there are many other reasons why public/private organizations are
aggressively adopting FOSS.
These include:
• Security
• Reliability/Stability
• Open standards and vendor independence
• Reduced reliance on imports
• Developing local software capacity
• Piracy, IPR, and the WTO
• Localization
FOSS LICENCE
The Free Software Foundation publishes lists of licenses.
The most popular of these licenses are:
a. GNU General Public License.
b. FreeBSD License. c. Mozilla Public License.
d. Apache License.
e. X11 License (also known as MIT License)
Initially, it was difficult for business to incorporate FOSS with propriety code but now several
licenses permit this combination.
By selecting appropriate license it quite possible to bundle the Free and Open Source Software
with the proprietary software.
Licenses, like the BSD and MIT Licenses, are suitable for situations in which originator wants
wide spread deployment of his/her ideas regardless of in open source software or proprietary
software.
The wide ranges of FOSS licenses give more flexibility to developers and distributors.

MIT ( Massachusetts Institute of Technology) licence


 The MIT license gives users express permission to reuse code for any purpose, sometimes
even if code is part of proprietary software. As long as users include the original copy of the
MIT license in their distribution, they can make any changes or modifications to the code to
suit their own needs.
 It is one of the most simple open source license agreements. The intent was for the text to
be understandable by average users and to avoid extensive litigation

As of 2020, the MIT License was the most popular software license found in one
analysis,continuing from reports in 2015 that the MIT License was the most popular software
license on GitHub.
BSD licenses
Are a low restriction type of license for open source software that does not put requirements on
redistribution.As a low restriction and requirement license type, Berkeley Source Distribution (BSD)
licenses are used for the distribution of many freeware, shareware and open source software. BSD
licenses are much like the license that accompanied the original BSD. The original BSD Unix license was
first written in 1969. There are 4 main clauses of the classic BSD license:

1. The BSD UNIX license states one may copy, modify and redistribute the code so long as one retains
a copy of the original copyright statement.
2. The copyright statements must include a clear statement of two restrictions for use of the distributed
software.
3. A disclaimer for limitations of liability that include not claiming authorship of the code where the
code was not written by the user and not suing the author of the program for unexpected or
undesirable functionality.
4. The stipulation that one doesn‘t use the name of the software or its authors to advertise or promote
work derived from modification of the distributed code without prior written consent.
Similarly, other BSD licenses can have these clauses but may not include them all. As a base, the first two
clauses are a part of any BSD license. There are two, three and four clause BSD licenses.

APHACHE LICNENCE

The Apache software license gives users permission to reuse code for nearly any purpose, including using
the code as part of proprietary software.
As with other open source licenses, the Apache license governs how end-users can utilize the software in
their own projects.
This license is a widely-used open source license, and like other permissive licenses, it continues to grow
in popularity because it encourages the use of open source software within proprietary projects.
A software license is defined as a legal agreement between an end-user and the owner of a particular
software program that details the terms and agreements for the use and distribution of the software.
Furthermore, a software license usually outlines how many times a particular software can be
downloaded, how much the use of the software costs, and the varying levels of source code access that
end-users can take advantage of. The software license is an extremely important factor in ensuring that
the legal and permissive rights of all involved parties of a software program are appropriately maintained.
The Apache 2.0 license is a particular type of open-source, permissive software license that ensures that
end-users are granted a license to any patent that is covered by the software in question. An Apache 2.0
license ensures the security and availability of safe and powerful open-source software.

Features Of The Apache 2.0 License


1) Commercial Use

Under the Apache 2.0 license, end-users can create their own proprietary software and offer the licensed
code of the original software to customers. End-users can utilize the Apache 2.0 license in any
commercially licensed software or enterprise application for free.
However, Apache trademarks must not be used in the licensed proprietary software or any of the
software‘s legal or organizational documentation. Studies show that the Apache 2.0 license is used by
approximately 31.1% of websites with known web servers.
2) Source Code Modification and Distribution

The Apache 2.0 license allows software developers to alter the source code of existing software‘s source
code, copy the original source code or update the source code. Furthermore, developers can then
distribute any copies or modifications that they make of the software‘s source code.

Users must include a copy of their Apache 2.0 license, a clear attribution to it, and clearly identifiable
modification notices on all altered files.
3) Establish Patent Claims
The terms of the Apache 2.0 license state that end-users are provided perpetual and non-exclusive rights
to patents and copyrights. Users are also permitted to create copyright statements for their modified
software‘s source code.

Furthermore, users can create their own specific terms and conditions for the use, distribution,
modification, and reproduction of their modified software as it does not necessarily need to be made
commercially available under the same software license.

GNU Genral Public Licence

GPL License is a free software license that allows software to be modified or redistributed without
any restrictions or compulsory payments for the licensed code. the GPL license is used by
Developers to ensure that their code does not become proprietary when modified.

The GNU General Public License is a free, copyleft license for software and other kinds of works.The
licenses for most software and other practical works are designed to take away your freedom to share and
change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free software for all its users. We, the
Free Software Foundation, use the GNU General Public License for most of our software; it applies also
to any other work released this way by its authors. You can apply it to your programs, too.

General Public Licenses are designed to make sure that you have the freedom to distribute copies of free
software (and charge for them if you wish), that you receive source code or can get it if you want it, that
you can change the software or use pieces of it in new free programs, and that you know you can do these
things.

To protect your rights, we need to prevent others from denying you these rights or asking you to surrender
the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you
modify it: responsibilities to respect the freedom of others.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to
the recipients the same freedoms that you received. You must make sure that they, too, receive or can get
the source code. And you must show them these terms so they know their rights.

Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the
software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free
software.

Some devices are designed to deny users access to install or run modified versions of the software inside
them, although the manufacturer can do so. Therefore, we have designed this version of the GPL to
prohibit the practice for those products.

Finally, every program is threatened constantly by software patents. States should not allow patents to
restrict development and use of software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could make it effectively proprietary. To
prevent this, the GPL assures that patents cannot be used to render the program non-free.

Models of Open Source and Free Software Development


The open source development model has key differences when compared to the traditional model
of developing software (collect requirements, design, implement, test, release, and maintain).

The open source development model, illustrated in the Figure, starts with an idea for a new project,
a new functionality or capability to an existing open source software component. Next step is to
provide a design for the implementation and then a prototype of the capability and translate it from
an idea into running software. At the moment the software runs, it is released as development
release, even though it may contain known and unknown bugs. This follows the spirit of release
early and release often.

The software will be tested by the community who discuss the software through mailing lists and
discussion boards and provide feedback, bug reports, and fixes through the project mailing list.
The feedback is recorded and taken into consideration by project members and maintainers to
improve the implementation and then a new development release will be available. This cycle
happens as many times as needed until project members feel that the implementation is stable
enough. When the implementation is released as stable, the development cycle continues to
happen with the development release (also called development tree) until a newer stable release is
available.

characteristics of the open source development model include:

 Bottom up development: Project members who do the most work get the most say when it
comes to making design and implementation decisions. Those that do the most work get the most
say. Relationships between developers are very important

 “Release early, release often”: Don‘t wait to have a fully working version to make the code
public and release a version of the software. This release philosophy allows for peer review,
where all members of the community can comment and offer suggestions and bug fixes.
 Peer Review: Members of the open source project review the code, provide comments and
feedback to improve the quality and functionality.
 Small, Incremental changes: In open source project development, often additional features are
small and non intrusive for good reasons: It is easier to understand small patches and code
changes.
 Features that ignore security concerns are flagged: The open source community takes
security very seriously and any development or capability that jeopardizes the security of the
software is flagged and not included in the software until the security concern is dealt with.

 Continuous quality improvement: This is due to the extensive peer review and quick bug fixes
 Test projects: In many cases, test projects are created for large open source projects to create
test suites and automate testing.

 End user involvement in the entire process.

Choosing an Open Source or Free Software License


An open source license is a legal document that specifies what people can and cannot do with your
project. For example, can someone modify your code and distribute it as their own? Can they
include your code as part of their own proprietary project? The open source license you choose
determines the answers to those questions.
GPL(GNU General Public License)
The original copyleft license (and oldest open source license in general) is the GNU General Public
License, or GPL. GPL was created in 1989 by the same developers who built the GNU operating
system, and is still one of the most popular open source licenses in use today. A 2015 analysis by
GitHub showed that about 25% of GitHub projects used GPL version 2 or version 3.
GPL is known as strong copyleft license. This means that any software that uses a project licensed
under GPL must also be licensed under GPL. Because GPL is an open source license, this means
that any project using even a bit of GPL-licensed software must also be open source.

UNIT – II BASICS OF PHP PROGRAMMING


Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
Variables
In PHP, a variable is declared using a $ sign followed by the variable name. PHP variable can't be
start with numbers and special symbols. PHP variables must start with letter or underscore only.
$variablename = value;
<?php
$a="hello";//letter (valid)
$_b="hello";//underscore (valid)

echo "$a <br/> $_b";


?>
Rules for declaring PHP variable:
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special
symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.

<?php

$str="hello string";

$x=200;

$y=44.6;

echo "string is: $str <br/>";

echo "integer is: $x <br/>";

echo "float is: $y <br/>";

?>

controls and functions

Control flow statements are used in programming to control the flow of code execution. In PHP,
there are several types of control flow statements, including if-else statement, switch statement, for
loop, while loop, and do-while loop. In this article, we‘ll go over each of these statements and
provide examples to help you understand their usage.

If-else statement
If-else statements are used to execute different code based on different conditions. Here is the
syntax for an if-else statement:

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
In some cases, you may need to evaluate multiple conditions. In these cases, you can use the else if
statement. Here is the syntax for multiple if-else statement:

if (condition1) {
// code to be executed if condition1 is true
} elseif (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
<?php
$num = 10;

if ($num < 5) {
echo "The number is less than 5.";
} elseif ($num == 5) {
echo "The number is equal to 5.";
} else {
echo "The number is greater than 5.";
}
?>
Switch statements are used to execute different code based on different values. Here is the syntax
for a switch statement:
switch (expression) {
case value1:
// code to be executed if expression is equal to value1
break;
case value2:
// code to be executed if expression is equal to value2
break;
default:
// code to be executed if expression is not equal to any of the values
}
<?php
$dayOfWeek = 'Tuesday';

switch ($dayOfWeek) {
case 'Monday':
echo 'Today is Monday';
break;
case 'Tuesday':
echo 'Today is Tuesday';
break;
case 'Wednesday':
echo 'Today is Wednesday';
break;
case 'Thursday':
echo 'Today is Thursday';
break;
case 'Friday':
echo 'Today is Friday';
break;
default:
echo 'It is the weekend';
}
?>
For loops are used to repeat a block of code a specific number of times. Here is the syntax for a for
loop:

for (initialization; condition; increment) {


// code to be executed
}
In a for loop, the initialization sets the starting point, the condition determines when to stop, and the
increment increases the counter. The code inside the curly braces is executed each time the loop
runs.
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i . " ";
}
?>
While loops are used to repeat a block of code as long as a condition is true. Here is the
syntax for a while loop:
while (condition) {
// code to be executed
}
<?php
$count = 1;
while ($count <= 5) {
echo $count . " ";
$count++;
}
?>
Do-while loops are similar to while loops, but the code inside the curly braces is executed
at least once, even if the condition is false. Here is the syntax for a do-while loop:

do {
// code to be executed
} while (condition);

<?php
$count = 1;
do {
echo $count . " ";
$count++;
} while ($count <= 5);
?>
foreach loop
The foreach loop is used to traverse the array elements. It works only on array and object. It will
issue an error if you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the
elements of an array.

foreach ($array as $value) {

//code to be executed

}
<?php
//declare array
$season = array ("Summer", "Winter", "Autumn", "Rainy");
foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>

PHP function
PHP function is a piece of code that can be reused many times. It can take input as argument list
and return value. There are thousands of built-in functions in PHP.

In PHP, we can define Conditional function, Function within Function and Recursive function also.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times, like in
other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic many times. By the use
of function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand
the flow of the application because every logic is divided in the form of functions.
We can declare and call user-defined functions easily.The syntax to declare user-defined functions.
Syntax
function functionname(){
//code to be executed
}
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
PHP Function Arguments
We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-
length argument list.
Let's see the example to pass single argument in PHP function.
<?php
function sayHello($name){
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
PHP Call By Reference
Value passed to the function doesn't modify the actual value by default (call by value). But we can do so
by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you need to use
ampersand (&) symbol before the argument name.
Let's see a simple example of call by reference in PHP.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>

An example of PHP function that returns value.


<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>

Basics of PHP Programming: Introduction – syntax and variables – controls and


functions – passing information between pages – strings – numbers – arrays,
array functions and advanced array functions
Passing Information Between Pages
There are two ways the browser client can send information to the web server.
The POST Method
The GET Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In
this scheme, name/value pairs are joined with equal signs and different pairs are separated by the
ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other non-alphanumeric characters
are replaced with a hexadecimal values. After the information is encoded it is sent to the server.
PHP $_POST is a PHP super global variable which is used to collect form data after submitting an
HTML form with method="post". $_POST is also widely used to pass variables.
The POST method does not have any restriction on data size to be sent.

The POST method can be used to send ASCII as well as binary data.

The data sent by POST method goes through HTTP header so security depends on HTTP protocol.
By using Secure HTTP you can make sure that your information is secure.

The PHP provides $_POST associative array to access all the sent information using POST method.
The example below shows a form with an input field and a submit button. When a user submits the
data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the
<form> tag. In this example, we point to the file itself for processing form data. If you wish to use
another PHP file to process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_POST to collect the value of the input field.
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an
HTML form with method="get".
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be sent to the server.
GET can't be used to send binary data, like images or word documents, to the server.
$_GET can also collect data sent in the URL.
<html>
<body bgcolor="cyan">
<h1><center>STUDENT MARK SHEET</h1>
<form action="mark.php" method="POST">
<table align="center" border="5" width="500">
<tr>
<td><b>NAME</td><td><input type="text" name="name"></td>
</tr>
<tr>
<td><b>REGISTER NUMBER</td><td><input type="text"
name="rno"></td>
</tr>
<tr>
<td><b>MARK 1</td><td><input type="text" name="m1"></td>
</tr>
<tr>
<td></td><td><input type="submit" name="submit" value="OK">
<input type="submit" name="submit" value="SUBMIT"></td>
</tr>
</table>
</form> </body> </html>
PHP file
<?php
$a=$_POST['name'];
$b=$_POST['rno'];
$m1=$_POST['m1'];
$res=($m1>=40)?"PASS":"FAIL";
Echo‖NAME: $a </br>REGISTER NUMBER : $</br>RESULT:$res";
?>

PHP Strings and Numbers


PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports only
256-character set and so that it does not offer native Unicode support. There are 4 ways to specify
a string literal in PHP.
 single quoted
 double quoted
 heredoc syntax
Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string
in PHP.

For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use
double backslash (\\). All the other instances with backslash such as \r or \n, will be output same as they
specified instead of having any special meaning.

<?php

$str='Hello text within single quote';

echo $str;

?>
We can store multiple line text, special characters, and escape sequences in a single-quoted PHP
string.

Example 2

<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>

Double Quoted
In PHP, we can specify string through enclosing text within double quote also. But escape
sequences and variables will be interpreted using double quote PHP strings.
Example 1
<?php
$str="Hello text within double quote";
echo $str;
?>
Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is
provided after this heredoc <<< operator, and immediately a new line is started to write any text.
To close the quotation, the string follows itself and then again that same identifier is provided.
That closing identifier must begin from the new line without any whitespace or tab.

<?php
$city = 'Delhi';
$str = <<<DEMO
Hello! My name is Arun, and I live in $city.
DEMO;
echo $str;
?>
Output : Hello! My name is Arun, and I live in Delhi.

strlen() - Return the Length of a String


The PHP strlen() function returns the length of a string.
<?php
echo strlen("Hello world!"); // outputs 12
echo str_word_count("Hello world!"); // outputs 2
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
PHP Integers
2, 256, -256, 10358, -179567 are all integers.
An integer is a number without any decimal part.
An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit
systems.
An integer must have at least one digit
An integer must NOT have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed
with 0x) or octal (8-based - prefixed with 0)
PHP has the following predefined constants for integers:

PHP_INT_MAX - The largest integer supported


PHP_INT_MIN - The smallest integer supported
PHP_INT_SIZE - The size of an integer in bytes
PHP has the following function to check if the type of a variable is integer: is_int().
PHP Arrays
An array is a data structure that stores one or more similar type of values in a single value.
For example if you want to store 100 numbers then instead of defining 100 variables its easy to
define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c
which is called array index.

Numeric array − An array with a numeric index. Values are stored and accessed in linear
fashion.
Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices

Numeric arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.

Example
Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>

Output
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three Value is four Value is five
Array Functions
PHP is very rich in terms of Buil-in functions. PHP Array Functions allow you to interact with and
manipulate arrays in various ways. PHP arrays are essential for storing, managing, and operating
on sets of variables.
array() : Create an array
array_change_key_case() : PHP array_change_key_case() function changes the case of all key of
an array.
<?php

$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

print_r(array_change_key_case($salary,CASE_UPPER));

?>

output : Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
count() : PHP count() function counts all elements in an array.
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?> output : 4
sort() : PHP sort() function sorts all the elements in an array.
<?php
$season=array("summer","winter","spring","autumn");
sort($season);
foreach( $season as $s )
{
echo "$s<br />";
}
?>
output : autumn spring summer winter
rsort() - Sort the elements of the $cars array in descending alphabetical order:
<?php
$numbers = array(4, 6, 2, 22, 11);
$arrlen = count($numbers);
rsort($numbers);
for($x = 0; $x < $arrlen; $x++)
{
echo $numbers[$x];
echo "<br>";
}
?>
O/P – 22
11
6
4
2
array_reverse() : PHP array_reverse() function returns an array containing elements in reversed
order.
<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
output : autumn spring winter summer

array_search() : PHP array_search() function searches the specified value in an array. It returns key
if search is successful.
<?php
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>
output : 2

array_intersect() : PHP array_intersect() function returns the intersection of two array. In other
words, it returns the matching elements of two array.
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
output : sonoo smith
array_chunk() : Splits an array into chunks of arrays
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43","Harry"=>"50");
echo ―array_chunk($age,2,true)‖;
?>
array_column() : Return the values from a single column in the input array
<?php
// An array that represents a possible record set returned from a database
$a = array(
array(
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
),
array(
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
)
);

$last_names = array_column($a, 'last_name');


echo ―$last_names‖;
?>
Output
Array
(
[0] => Griffin
[1] => Smith
)
array_sum() - The array_sum() function returns the sum of all the values in the array.
<?php
$a=array(5,15,25);
echo array_sum($a);
?>
O/P - 45
array_product() : Calculates the product of the values in an array
<?php
$a=array(5,5);
echo(array_product($a));
?>
O/P – 25
sizeof()- Return the number of elements in an array:
<?php
$a1=array("red","green","blue","yellow");
echo sizeof($a1);
?>
O/P – 4

Advanced array function


array_ replace() - Replace the values of the first array ($a1) with the values from the second array
($a2):
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
foreach( array_replace($a1,$a2) as $n )
{
echo "$n<br />";
}
?>
O/P - blue yellow
current(),next(),end() - Output the value of the current ,next and the last element in the array:
<?php
$a1=array("red","green","blue","yellow","white");
echo current($a1) ."<br>";
echo next($a1)."<br>";
echo end($a1);
?>
O/P – red green white

list() - The list() function is used to assign values to a list of variables in one operation.
<?php
$my_array = array("Red","Yellow","Green","Blue");
list($a, , ,$d) = $my_array;
echo "Here I only use the $a and $d variables.";
?>
o/p - Here I only use the Red and Blue variables.
array_pop() :Deletes the last element of an array
<?php
$a=array("red","green","blue");
echo array_pop($a);
?>
O/P – blue
array_push() : Inserts one or more elements to the end of an array
<?php
$a=array("red","green","blue");
array_push($a,"white","yellow");
foreach( $a as $n )
{
echo "$n<br />";
}
?>
O/P – red green blue white yellow
array_merge() : Merges one or more arrays into one array
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
$res=array_merge($a1,$a2);
foreach( $res as $n )
{
echo "$n<br />";
} ?>
O/P – red green blue yellow

You might also like