Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - PHP Built-in Functions for Arrays

By: FYICenter.com

Part:   1  2  3  4   5  6  7 

(Continued from previous part...)

How To Use an Array as a Queue?

A queue is a simple data structure that manages data elements following the first-in-first-out rule. You use the following two functions together to use an array as a queue:

  • array_push($array, $value) - Pushes a new value to the end of an array. The value will be added with an integer key like $array[]=$value.
  • array_shift($array) - Remove the first value from the array and returns it. All integer keys will be reset sequentially starting from 0.

Here is a PHP script on how to use an array as a queue:

<?php
$waitingList = array();
array_push($waitingList, "Jeo");
array_push($waitingList, "Leo");
array_push($waitingList, "Kim");
$next = array_shift($waitingList);
array_push($waitingList, "Kia");
$next = array_shift($waitingList);
array_push($waitingList, "Sam");
print("Current waiting list:\n");
print_r($waitingList);
?>

This script will print:

Current waiting list:
Array
(
    [0] => Kim
    [1] => Kia
    [2] => Sam
)

How To Use an Array as a Stack?

A stack is a simple data structure that manages data elements following the first-in-last-out rule. You use the following two functions together to use an array as a stack:

  • array_push($array, $value) - Pushes a new value to the end of an array. The value will be added with an integer key like $array[]=$value.
  • array_pop($array) - Remove the last value from the array and returns it.

Here is a PHP script on how to use an array as a queue:

<?php
$waitingList = array();
array_push($waitingList, "Jeo");
array_push($waitingList, "Leo");
array_push($waitingList, "Kim");
$next = array_pop($waitingList);
array_push($waitingList, "Kia");
$next = array_pop($waitingList);
array_push($waitingList, "Sam");
print("Current waiting list:\n");
print_r($waitingList);
?>

This script will print:

Current waiting list:
Array
(
    [0] => Jeo
    [1] => Leo
    [2] => Sam
)

How To Randomly Retrieve a Value from an Array?

If you have a list of favorite greeting messages, and want to randomly select one of them to be used in an email, you can use the array_rand() function. Here is a PHP example script:

<?php
$array = array("Hello!", "Hi!", "Allo!", "Hallo!", "Coucou!");
$key = array_rand($array);
print("Random greeting: ".$array[$key]."\n");
?>

This script will print:

Random greeting: Coucou!

(Continued on next part...)

Part:   1  2  3  4   5  6  7 


Selected Developer Jobs:

More...