Array In PHP: In Brief

Share Now

#ARRAY INTRODUCTION

$studentDetails = array(
    "Nahid",
    "Mahamud",
    8247,
    "DRMC"
);

//this is fine too
$studentDetails2 = [
    "Nahid",
    "Mahamud",
    8247,
    "DRMC"
];

$n = count($studentDetails);

for( $i=0; $i<$n; $i++ ){

    echo $studentDetails[$i]."\n";
}

#ARRAY MANIPULATION
change or modify a value of an existing array

$studentDetails[1] = "Hridoy"; //will replace Mahamud with Hridoy

#array_pop():
Array Pop removes the last item from an array and returns it.

$last_item = array_pop($studentDetails);
echo $last_item."\n";

#array_shift():
Array Shift removes the first item from an array and returns it.

$first_item = array_shift($studentDetails);
echo $first_item."\n";

#array_push():
Add new data at the end of the Array.

//array_push(arrayname,data);
array_push($studentDetails,CSE);

#array_unshift():
Add new data at the first of the Array.

//array_unshift(arrayname,data);
array_unshift($studentDetails,Male);

#Associative Array:

$myDetails = [
    'First Name'=>'Nahid',
    'Last Name'=>'Mahamud',
    'College No'=>'8247'
];

echo $myDetails['College No'];

#Associative Array

$foods = [
    'vegetables' => 'capsicum, carrot, potato, raddish',
    'fruits' => 'apple, orange, banana, grape',
    'drinks' => 'water, smoothie, juice',
];
echo "\n";
//show one data
echo $foods['vegetables'];
echo "\n";

//show all data
foreach ( $foods as $key => $value ) {
    echo $key."=".$value."\n";
}

//another way
$keys = array_keys($foods);
print_r($keys); //use to print array

#Array to String and String to Array

//STRING TO ARRAY
$language = explode(', ','bangla, english, gemran');
var_dump($language);
echo $language[2];
echo "\n";

//ARRAY TO STRING
$languageStirng =  join(', ',$language);
echo $languageStirng;

#Multi-Dimensional Array:

//MULTIDIMENSIONAL ARRAY
$foods = [
    'vegetables' => explode(',','capsicum, carrot, potato, raddish'),
    'fruits' => explode(',','apple, orange, banana, grape'),
    'drinks' => explode(',','water, smoothie, juice'),
];
echo "\n";

print_r($foods);

#Array to JSON:


$stdDetails = [
    'First Name'=>'Nahid',
    'Last Name'=>'Mahamud',
    'College No'=>'8247'
];

$jsonData = json_encode($stdDetails);
echo "\n";
echo $jsonData;
$jsonDataDecode = json_decode($jsonData,true);
echo "\n";
print_r ($jsonDataDecode);

#Array[copy by value & copy by reference]:

$person = [
    'fname' => 'Nahid',
    'lname' => 'Mahamud',
];

$newperson = $person;//copy by value
/**
 * SHALLOW COPY IS MORE LIKE POINTER IN C
 */
$newperson = &$person;//cooy by reference/shallow copy -> changes value in both arrays
$newperson['lname'] = 'Hridoy';

print_r ($newperson);
print_r ($person);
[/code]

<strong>#Remove data from Associative Array:</strong> use <code>unset</code> to remove data from associative array
[code]
$person = [
    'fname' => 'Nahid',
    'lname' => 'Mahamud',
];
print_r($person);
unset($person['lname']);
print_r($person);

#Extractdata from An Array: use array_slice() to extract data from normal/associative array.

/**
 * extract data from an array
 */

$prDetails = [
    "Nahid",
    "Mahamud",
    8247,
    "DRMC",
];

//$extractedData = array_slice($prDetails,2);
/**
 * array_slice(array_name, from where to slice, how many items)
 * true, preserve offset key of the actual array
 */
$extractedData = array_slice($prDetails,2,1,true);
print_r($extractedData);

/**
 * EXTRACT DATA FROM ASSOCIATIVE ARRAY
 */
$personx = [
    'fname' => 'Nahid',
    'lname' => 'Mahamud',
    'collegeNo' => 8247,
    'homeTown' => 'Tangail',
    'gneder' => 'Male'
];

$personExtractData = array_slice($personx,2,null,true);
print_r($personExtractData);

#Array_Splice():

/**
 * array_splice()-> extract and remove data from an array
 */

$personRemoveData = array_splice($personx,2,2,true);
print_r($personRemoveData);
/**
 * array_splice()-> extract and remove data from an array
 * and then insert some data
 */

$personx2 = [
    'fname' => 'Nahid',
    'lname' => 'Mahamud',
    'collegeNo' => 8247,
    'homeTown' => 'Tangail',
    'gneder' => 'Male'
];

 $newInfo = [
    'hobby' => 'coding',
    'position' => 'CEO',
 ];

 $personDataUpdated = array_splice($personx2,2,2,$newInfo);
 print_r($personDataUpdated);
 print_r($personx2);

#Sort In Array:

 /**
  * SORT IN ARRAY
  * SORT DONOT PRESRVE KEY
  * Use asort() in order to preserve key
  * arsort() -> use in case you need reverse sort
  * ksort() -> use in case you need sorting based on key
  * krsort() -> use in case you need reverse sorting based on key
  */

  $favFruits = ['apple','banana','orange','favOne'=>'guava','lichi','mango'];
  sort($favFruits);
  print_r($favFruits);

  asort($favFruits);
  print_r($favFruits);

  $randu = ['apple','Alpine','anaconda','Banana','Ballon','cat','Cow','zoo','Giraffe'];
  sort($randu);
  print_r($randu);

  //sort based on string and  case insensetive
  sort($randu, SORT_STRING | SORT_FLAG_CASE);
  print_r($randu);

#Search In Array:

/**
 * search in array
 */

$randu = ['apple','Alpine','anaconda','b'=>'Banana','Ballon','cat','zoo','Giraffe'];
if(in_array('zoo',$randu)){
    echo "HURRAY!!! WE GOT IT";
}else {
    echo "NOT FOUND";
}
echo "\n";

$searchPosition = array_search('zoo',$randu);
echo "We found it on ".$searchPosition."th position";
echo "\n";

/**
 * search key in array
 */
if( key_exists('bx',$randu) ){
    echo "KEY EXISTS";
} else {
    echo "Key Not Found";
}

#Array Difference & Intersection:

/**
 * Identitify common element in array
 */

 $ourNumber1 = [1,2,33,4,567,12,13,221,233];
 $ourNumber2 = [11,122,31,04,567,112,123,221];

 $common =array_intersect($ourNumber1,$ourNumber2);
 print_r($common);

 $ourFruit1 = ['a'=>'apple', 'b'=>'banana','l'=>'lemon','o'=>'orange'];
 $ourFruit2 = ['a'=>'apricut', 'b'=>'banana','LM'=>'lemon','o'=>'olive'];

 $commonf =array_intersect($ourFruit1,$ourFruit2);
 print_r($commonf);
//ALSO CHECK WITH KEY
 $commonf2 =array_intersect_assoc($ourFruit1,$ourFruit2);
 print_r($commonf2);

 /**
  * CHECK DIFFERENCE IN AN ARRAY
  */

  $diff = array_diff($ourFruit1,$ourFruit2);
  print_r($diff);

  //also check diff with key
  $diff = array_diff_assoc($ourFruit1,$ourFruit2);
  print_r($diff);

#Utility Functions Of Array:

/**
 * UTILITY FUNCTIONS OF ARRAY
 * array_walk() -> doesn't modify  array
 */
 $unumber = [1,23,2,22,11,3,32,12,11,8,47];

 //will show square of aall elemnts
 function numberSquare($num) {
    printf("Sqaure of %d is %d \n",$num, $num*$num);
 }
/**
 * UTILITY FUNCTIONS OF ARRAY
 * array_map() -> will modify array
 */

 //will return cube
 function numberCube($num) {
    return $num*$num*$num;
 }

 array_walk($unumber,'numberSquare');

 $newArray = array_map('numberCube', $unumber);

 print_r($newArray);

 /**
 * UTILITY FUNCTIONS OF ARRAY
 * array_filter() -> will update array
 */

 //check even
 function checkEven( $n ) {
    $edata = (($n % 2) == 0) ? true:false;
    return $edata;
 }

 //check odd
 function checkOdd( $n ) {
    $edata = (($n % 2) !== 0) ? true:false;
    return $edata;
 }

 //here checkEven is a callback function
 //here checkOdd is a callback function
 $newArray = array_filter($unumber,'checkEven'); 
 $newArray2 = array_filter($unumber,'checkOdd'); 

 print_r($newArray);
 print_r($newArray2);

 /**
  * you can treat any string as an array
  */
 $personName = ['clerk','bruce','banner','barry','kal','tony'];
 
 //check name by b
 function checkNameByb( $name ){
    return $name[0] == 'b';
 }

 $nameWithb = array_filter($personName,'checkNameByb');

 print_r($nameWithb);

 /**
  * ARRAY UTILITY FUCNTION
  * array_reduce -> will do operation on an array then will reduce it
  */
 $rnumber = [1,2,3,4];

 /**
  * this fucntion will show sum
 */
 function sum($oldVal = 0, $newVal) {
    return $oldVal+$newVal;
 }

/**
  * this fucntion will show sum of even numbers
 */
function sumEven($oldVal = 0, $newVal) {
    if( $newVal % 2 == 0 ){
        return $oldVal+$newVal;
    } else{
        return $oldVal;
    }
 }

 $sum = array_reduce($rnumber,'sum'); //sum is callback function
 $sumE = array_reduce($rnumber,'sumEven'); //sumEven is callback function

 echo $sum;
 echo "\n";
 echo $sumE;

#List Function In Array:

/**
 * LIST FUCNTION IN ARRAY
 */

$studentDetails = [
    "Nahid",
    "Mahamud",
    8247,
    "DRMC",
];

list( $firstName, $lastName, $collegeNo, $college ) = $studentDetails;
echo $college;

#Range Function In Array:

/**
 * RANGE FUNCTION AND STEPPING IN ARRAY
 */
 //will print 1 to 20
 $numberRange = range(1,20);
 /**
  * range(frist,last,step)
  */
 $numberRangeEven = range(1,20,3);

 print_r($numberRange);
 print_r($numberRangeEven);

#Shuffle In Array:


#Array Shuffle:

/**
   * ARRRAY SHUFFLE
   * normally will not preserve key in associative array
   */

  $personx = [
    'fname' => 'Nahid',
    'lname' => 'Mahamud',
    'collegeNo' => 8247,
    'homeTown' => 'Tangail',
    'gneder' => 'Male'
];
 shuffle($personx);
 print_r($personx);

 /**
  * WILL SHOW A RANDOM VALUE FROM AN ARRAY
  */

  $personxr = [
    'fname' => 'Nahid',
    'lname' => 'Mahamud',
    'collegeNo' => 8247,
    'homeTown' => 'Tangail',
    'gneder' => 'Male'
];
$key = array_rand($personxr);
echo $personxr[$key];

/**
 * another way
 * make a temporary array
 */


$_personxr = $personxr;
shuffle($_personxr);
print_r($_personxr);

#Remove Empty Values From Array:

$wp_day[] = get_field( 'w_day' ); //acf filed values -> from foreach loop to an array
$unique_dates = array_unique($wp_day); //make the array unique
$unique_dates = array_values(array_filter($unique_dates)); //remove empty values
Picture of Nahid Mahamud

Nahid Mahamud

Web Developer | Graphic Designer | WordPress & Woo-commerce Expert