PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column.
Definition
$emp = array
(
array(1,”sonoo”,400000),
array(2,”john”,500000),
array(3,”rahul”,300000)
);
PHP Multidimensional Array Example
Let’s see a simple example of PHP multidimensional array to display following tabular data. In this example, we are displaying 3 rows and 3 columns.
PHP allows you to associate name/label with each array elements in PHP using => symbol. Such way, you can easily remember the element because each element is represented by label than an incremented number.
PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0.
PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable.
Advantage of PHP Array
Less Code: We don’t need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.
PHP Array Types
There are 3 types of array in PHP.
Indexed Array
Associative Array
Multidimensional Array
PHP Indexed Array
PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.
PHP Parameterized functions are the functions with parameters. You can pass any number of parameters inside a function. These passed parameters act as variables inside your function.
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the function.
PHP Parameterized Example 1
Addition and Subtraction
In this example, we have passed two parameters $x and $y inside two functions add() and sub().
<!DOCTYPE html>
<html>
<head>
<title>Parameter Addition and Subtraction Example</title>
</head>
<body>
<?php
//Adding two numbers
function add($x, $y) {
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);
//Subtracting two numbers
function sub($x, $y) {
$diff = $x - $y;
echo "Difference between two numbers is = $diff";
}
sub(943, 467);
?>
</body>
</html>
Output:
PHP Parameterized Example 2
Addition and Subtraction with Dynamic number
In this example, we have passed two parameters $x and $y inside two functions add() and sub().
Â
<?php
//add() function with two parameter
function add($x,$y)
{
$sum=$x+$y;
echo "Sum = $sum <br><br>";
}
//sub() function with two parameter
function sub($x,$y)
{
$sub=$x-$y;
echo "Diff = $sub <br><br>";
}
//call function, get two argument through input box and click on add or sub button
if(isset($_POST['add']))
{
//call add() function
add($_POST['first'],$_POST['second']);
}
if(isset($_POST['sub']))
{
//call add() function
sub($_POST['first'],$_POST['second']);
}
?>
<form method="post">
Enter first number: <input type="number" name="first"/><br><br>
Enter second number: <input type="number" name="second"/><br><br>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
</form>
Output:
We passed the following number,
Now clicking on ADDITION button, we get the following output.
Now clicking on SUBTRACTION button, we get the following output.
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.
PHP User-defined Functions
We can declare and call user-defined functions easily. Let’s see the syntax to declare user-defined functions.
Syntax
 Â
function functionname(){
//code to be executed
}
Note: Function name must be start with letter and underscore only like other labels in PHP. It can’t be start with numbers or special symbols.
PHP Functions Example
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:Hello PHP 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.
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old
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.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello Call By Reference
PHP Function: Default Argument Value
We can specify a default argument value in function. While calling PHP function if you don’t specify any argument, it will take the default argument. Let’s see a simple example of using default argument value in PHP function.File: functiondefaultarg.php
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
PHP Function: Returning Value
Let’s see an example of PHP function that returns value.File: functiondefaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
PHP constants are name or identifier that can’t be changed during the execution of the script except for magic constants, which are not really constants. PHP constants can be defined by 2 ways:
Using define() function
Using const keyword
Constants are similar to the variable except once they defined, they can never be undefined or changed. They remain constant across the entire program. PHP constants follow the same PHP variable rules. For example, it can be started with a letter or underscore only.
Conventionally, PHP constants should be defined in uppercase letters.
Note: Unlike variables, constants are automatically global throughout the script.
PHP constant: define()
Use the define() function to create a constant. It defines constant at run time. Let’s see the syntax of define() function in PHP.
define(name, value, case-insensitive)
name: It specifies the constant name.
value: It specifies the constant value.
case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It means it is case sensitive by default.
Let’s see the example to define PHP constant using define().
Hello JavaTpoint PHP
Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message
PHP constant: const keyword
PHP introduced a keyword const to create a constant. The const keyword defines constants at compile time. It is a language construct, not a function. The constant defined using const keyword are case-sensitive.
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
Output:
Hello const by JavaTpoint PHP
Constant() function
There is another way to print the value of constants using constant() function instead of using the echo statement.
Syntax
The syntax for the following constant function:
constant (name)
<?php
define("MSG", "JavaTpoint");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>
Output:
JavaTpoint
JavaTpoint
Constant vs Variables
Constant
Variables
Once the constant is defined, it can never be redefined.
A variable can be undefined as well as redefined easily.
A constant can only be defined using define() function. It cannot be defined by any simple assignment.
A variable can be defined by simple assignment (=) operator.
There is no need to use the dollar ($) sign before constant during the assignment.
To declare a variable, always use the dollar ($) sign before the variable.
Constants do not follow any variable scoping rules, and they can be defined and accessed anywhere.
Variables can be declared anywhere in the program, but they follow variable scoping rules.
Constants are the variables whose values can’t be changed throughout the program.
In JavaScript, Math is a built-in object which includes properties and methods for mathematical operations. We can use the Math object to perform simple and complex arithmetic operations.
Note: Math works with the JavaScript Number type only.
In Math object, All the properties and methods are static. So, we don’t need to create its object to use its property or method. Also, even if we want, we cannot create an object as Math is not a constructor function.
Using JavaScript Math
Suppose, we want to get the value of PI for geometric calculation or the square root of a number in our program then we can use Math object. Let’s see how:
let pi = Math.PI;
document.write(pi + "<br/>");
let sqrt = Math.sqrt(9);
document.write(sqrt);
3.141592653589793 3
JavaScript provides a rich set of Math properties that can be used to get predefined constant values.
JavaScript Math Properties
Following are the properties provided by the JavaScript Math object:
Property
Description
E
holds Euler number whose value is 2.718(approx)
LN2
holds a natural logarithm of 2 whose value is 0.693(approx).
LN10
holds a natural logarithm of 10, whose value is 2.302(approx).
LOG2E
holds the base-2 logarithm of E have value1.442(approx)
LOG10E
holds the base-10 logarithm of E having value 0.434(approx)
PI
holds the numerical value of PI, whose approx value is 3.142
SQRT1_2
holds the square root of 1/2, whose approx value is 0.707
SQRT2
holds the square root of 2, having approx value 1.414
Let’s take an example to see how we can use these properties.
var e = Math.E
document.write(e +"<br>")
var ln2 = Math.LN2
document.write(ln2 +"<br>")
var ln10 = Math.LN10
document.write(ln10 +"<br>")
var sq = Math.SQRT1_2
document.write(sq +"<br>")
Suppose, we want to find min and max numeric value from the random number of list then it can be very easy by using Math object. See the below example.
// Find minimum number
var min = Math.min(10,25,47,23,18,8,21,30)
document.write(min +"<br>")
// Find maximum number
var max = Math.max(10,25,47,23,18,8,21,30)
document.write(max +"<br>")
8 47
JavaScript Math Methods
JavaScript Math Object provides a rich set of methods that are used to make math calculation easy and helps to reduce effort and time in math-oriented programming. Here we have listed the most commonly used Math object methods:
So to use Math object properties or methods, we do not have to create an object using the new keyword, and we can directly use the properties and methods in our code.
In this article, you’ll learn about functions, what a function is, the syntax, components, and types of functions. Also, you’ll learn to create a function in Python.
What is a function in Python?
In Python, a function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
Above shown is a function definition that consists of the following components.
Keyword def that marks the start of the function header.
A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of the function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
An optional return statement to return a value from the function.
Example of a function
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
How to call a function in python?
Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
Note: Try running the above code in the Python program with the function definition to see the output.
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet('Paul')
Docstrings
The first string after the function header is called the docstring and is short for documentation string. It is briefly used to explain what a function does.
Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines. This string is available to us as the __doc__ attribute of the function.
For example:
Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)
This function greets to
the person passed in as
a parameter
The return statement
The return statement is used to exit a function and go back to the place from where it was called.
Syntax of return
return [expression_list]
This statement can contain an expression that gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.
For example:
>>> print(greet("May"))
Hello, May. Good morning!
None
Here, None is the returned value since greet() directly prints the name and no return statement is used.
Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
Output
2
4
How Function works in Python?
Working of functions in Python
Scope and Lifetime of variables
Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function are not visible from outside the function. Hence, they have a local scope.
The lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.
Here is an example to illustrate the scope of a variable inside a function.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output
Value inside function: 10
Value outside function: 20
Here, we can see that the value of x is 20 initially. Even though the function my_func() changed the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the one outside. Although they have the same names, they are two different variables with different scopes.
On the other hand, variables outside of the function are visible from inside. They have a global scope.
We can read these values from inside the function but cannot change (write) them. In order to modify the value of variables outside the function, they must be declared as global variables using the keyword global.
Types of Functions
Basically, we can divide functions into the following two types:
Built-in functions – Functions that are built into Python.
User-defined functions – Functions defined by the users themselves.
In this article, you will learn to pass objects to a function and return object from a function in C++ programming.
In C++ programming, objects can be passed to a function in a similar way as structures.
How to pass objects to a function?
Example 1: Pass Objects to Function
C++ program to add two complex numbers by passing objects to a function.
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void readData()
{
cout << "Enter real and imaginary number respectively:"<<endl;
cin >> real >> imag;
}
void addComplexNumbers(Complex comp1, Complex comp2)
{
// real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
real=comp1.real+comp2.real;
// imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
imag=comp1.imag+comp2.imag;
}
void displaySum()
{
cout << "Sum = " << real<< "+" << imag << "i";
}
};
int main()
{
Complex c1,c2,c3;
c1.readData();
c2.readData();
c3.addComplexNumbers(c1, c2);
c3.displaySum();
return 0;
}
Output
Enter real and imaginary number respectively:
2
4
Enter real and imaginary number respectively:
-3
4
Sum = -1+8i
How to return an object from the function?
In C++ programming, object can be returned from a function in a similar way as structures.
Example 2: Pass and Return Object from the Function
In this program, the sum of complex numbers (object) is returned to the main() function and displayed.
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(): real(0), imag(0) { }
void readData()
{
cout << "Enter real and imaginary number respectively:"<<endl;
cin >> real >> imag;
}
Complex addComplexNumbers(Complex comp2)
{
Complex temp;
// real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
temp.real = real+comp2.real;
// imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
temp.imag = imag+comp2.imag;
return temp;
}
void displayData()
{
cout << "Sum = " << real << "+" << imag << "i";
}
};
int main()
{
Complex c1, c2, c3;
c1.readData();
c2.readData();
c3 = c1.addComplexNumbers(c2);
c3.displayData();
return 0;
}