How can i implement QUEUE in PHP?

In circular queue, we can use empty data cell again when we remove the cell value using dequeue. Another important things is we can not add value before the head index( example if my array size is 5 and head point to index 0, then we need to empty the array index 4. means we can add 4 value when array size is 5). We can use this queue implementation in banking software( ex: give token to customers and call them according to that token). Here is the complete code below:

$devisor  = 5;
$data_array = [];
$head = 0;
$tail = 0;

function enqueue( $item = NULL ){
	global $head, $tail, $data_array, $devisor;
	if(empty($item)){
		echo 'invalid function call. Need to pass item as a function parametter';
		return;
	}
	$tail = $tail % $devisor;
	$next_tindex = $tail + 1;
	if( $head == $next_tindex % $devisor){
		echo 'Queue is full';
		return;
	}else{
		$data_array[$tail] = $item;
		$tail++;
	}
	return $data_array;
}

function dequeue(){
	global $head,$tail,$devisor,$data_array;
	if($tail == $head){
		echo 'Queue is empty';
		return -1;
	}
	
	$item = $data_array[$head];
	$head = ++$head % $devisor;
	return $item;
}

echo '<pre>';
print_r(enqueue(1));
echo '</pre>';
echo '<pre>';
print_r(dequeue());
echo '</pre>';

Leave a Reply

Your email address will not be published. Required fields are marked *