Home Logic Ubuntu (Linux) Blog PHP Fiddle

PHP: Array Functions

PHP has many predefined array functions. These functions make it a lot easier to work with arrays. Now, I will show you a few...



  Array Max

We use the max array function to find the highest value in an array.

// PHP max function syntax
max($array);


Example:

Create an array to store test scores. Return the highest test score.


// declare scores array
$scores= array(86,66,74,98,83);

// calculate highest score
$highest_score = max($scores);

// Print Highest Score
echo $highest_score;
  
Try running the appove code: PHP Fiddle

Output:



  Array Min

We use the min array function to find the smallest value in an array.

// PHP min function syntax
min($array);


Example:

Create an array to store test scores. Return the lowest test score.


// declare scores array
$scores= array(86,66,74,98,83);

// calculate lowest score
$lowest_score = min($scores);

// Print Highest Score
echo $lowest_score;
  
Try running the appove code: PHP Fiddle

Output:



  Array Rand

We use the array_rand function to randomly select a value in an array. It returns the array key.

// PHP array_rand function syntax
array_rand($array);

There is a second optional argument. An integer repersenting how many values we want to select.

array_rand($array,integer);

Example:

Create an array to store test scores. Randomly return two test scores.


// declare scores array
$scores= array(86,66,74,98,83);

/* 2 random keys: $rand_keys is an
index array of keys */
$rand_keys = array_rand($scores, 2);

// key to our first value
$return_key_1 = $rand_keys[0];

// key to our second value
$return_key_2 = $rand_keys[1];

// Print the scores
echo "Score 1: $scores[$return_key_1] \n
Score 2: $scores[$return_key_2] ";
  
Try running the appove code: PHP Fiddle

Output:

Since the return values are random, the output should change each time you run the code. Try it out on PHP Fiddle

  Comprehension Check


************************
1) Watch my Logic Videos
2) Complete the set theory homework
*************************