Friday, September 6, 2019

PHP Array Function Part - 1


PHP Array Function Part - 1

count()
It is use for count number of values in an array variable.
Syntax:
count(array_variable, mode)
Here mode is optional parameter. Two modes are here: 0 & 1. By default, 0 works
0 means, it will count only array value but will not count multidimesional values.
1 means, it will count all values with miltidimensional

For example,
$studentData = array('Suresh Kumar'=>array(22, 550), 'Sarita Khanna'=>array(24, 650), 'Mohan Sinha'=>array(20, 570), 'Kamlesh'=>array(26, 620));
echo "Without mode: ".count($studentData).'<br/>';
echo "With mode: ".count($studentData, 1);

Answer will be:
Without mode: 4
With mode: 12


end()
It is use to display last element in an array.
Syntax:
end(array_variable)

For example,
$student = array('Suresh Kumar', 'Sarita Khanna', 'Mohan Sinha', 'Kamlesh');
echo end($student);

Answer will be: Kamlesh

current()
It is use to display first element in an array.
Syntax:
current(array_variable)

For example,
$student = array('Suresh Kumar', 'Sarita Khanna', 'Mohan Sinha', 'Kamlesh');
echo current($student);

Answer will be: Suresh Kumar


array_sum()
It will sum all the values in an array.
Syntax:
array_sum(array_variable)

For example,
$makrs = array(50, 40, 60, 70, 90);
echo array_sum($makrs);

Answer will be: 310



array_combine()
It combines two array and make new array as pair of key and value. The first array works as key and second array works as value.
Syntax:
array_combine(array_variable1, array_variable2)

For Example,
$studentName = array('Amit', 'Mahesh', 'Sahil', 'Rohit', 'Komal');
$marks = array(50, 40, 60, 70, 90);
echo "<pre>";
print_r(array_combine($studentName, $marks));

Array
(
    [Amit] => 50
    [Mahesh] => 40
    [Sahil] => 60
    [Rohit] => 70
    [Komal] => 90
)



array_merge()
It will merge two or more array variables in one array variable. Here value of the second array variable always append at end of first array variable.

Syntax:
array_merge(array_variable1, array_variable2)

For Example,
$studentName = array('Amit', 'Mahesh', 'Sahil', 'Rohit', 'Komal');
$marks = array(50, 40, 60, 70, 90);

echo "<pre>";
print_r(array_merge($studentName, $marks));
Array
(
    [0] => Amit
    [1] => Mahesh
    [2] => Sahil
    [3] => Rohit
    [4] => Komal
    [5] => 50
    [6] => 40
    [7] => 60
    [8] => 70
    [9] => 90
)




array_diff()
It compares two or more array variable and always returns the value from the first array variable, which is not present in any of the other array variable.

Syntax:
array_diff(array_variable1, array_variable2)

For Example,
$studentName1 = array('Amit', 'Mahesh', 'Sahil', 'Rohit', 'Komal');
$studentName2 = array('Amit', 'Mahesh', 'Mohit', 'Rohit', 'Komal');

echo "<pre>";
print_r(array_diff($studentName1, $studentName2));

Array
(
    [2] => Sahil
)

No comments:

Post a Comment