Friday, September 6, 2019

PHP Array Function Part - 2


PHP Array Function Part - 2


array_flip()
It use to interchange the key and values of an array variable. Here key will make value and value will make key.
Syntax:
array_flip(array_variable)

For Example,
$array_data = array('Sunil'=>25, 'Mukesh'=>24, 'Dinesh'=>34, 'Kamlesh'=>15);
$new_array_data = array_flip($array_data);

echo "<pre>";
print_r($new_array_data);

Answer is:
Array
(
    [25] => Sunil
    [24] => Mukesh
    [34] => Dinesh
    [15] => Kamlesh
)


array_pop()
It removes last element of an array. If array variable will be empty, then it will return NULL.

Syntax:
array_pop(array_variable)

For Example,
$array_data = array('Cat', 'Dog', 'Lion', 'Bird');
array_pop($array_data);

echo "<pre>";
print_r($array_data);

Answer is:
Array
(
    [0] => Cat
    [1] => Dog
    [2] => Lion
)


array_push()
It will appends given values at end of an array. We can add more than one values at a time.

Syntax:
array_push(array_variable, value1, value2,...)

For Example,
$array_data = array('Cat', 'Dog');
array_push($array_data , 'Lion', 'Fox', 'Goat');

echo "<pre>";
print_r($array_data);

Answer is:
Array
(
    [0] => Cat
    [1] => Dog
    [2] => Lion
    [3] => Fox
    [4] => Goat
)



array_slice()
It will gave you slice of an array from where you want. Here we can give start point(from where slice will start) and length(how much will slice). If we will give only start then it will start slicing from given point to till end of the array.

Syntax:
array_slice(array_variable, start, length)

Fox Example,
$array_data = array('Cat', 'Dog', 'Lion', 'Fox', 'Goat');
$new_array_data = array_slice($array_data , 2, 2);

echo "<pre>";
print_r($new_array_data);

Answer is:
Array
(
    [0] => Lion
    [1] => Fox
)

array_unique()
It removes duplicate values from an array variable.

Syntax:
array_unique(array_variable)

For Example,
$array_data = array('Cat', 'Dog', 'Cat', 'Fox', 'Dog');
$new_array_data = array_unique($array_data);

echo "<pre>";
print_r($new_array_data);

Answer is:
Array
(
    [0] => Cat
    [1] => Dog
    [3] => Fox
)


sort()
It will sort array values in ascending order. 

Syntax:
sort($array_variable)

For Example,
$array_data = array('Dog', 'Cat', 'Fox', 'Lion');
sort($array_data);

echo "<pre>";
print_r($array_data);

Answer is:
Array
(
    [0] => Cat
    [1] => Dog
    [2] => Fox
    [3] => Lion
)


in_array()
It will search the given string is available in array or not. It is case-sensitive.

Syntax:
in_array(search_string, array_variabale)

For Example,
$array_data = array('Dog', 'Cat', 'Fox', 'Lion');
if(in_array('Dog', $array_data)){
echo "Found";
}else{
echo "Not Found";
}

No comments:

Post a Comment

Copyright © 2019 Tech Location BD. All Right Reserved