Selecting random element from PHP associative array

We will solve the exercise “Greet the guests” by selecting random element from PHP associative array

Here is the code with explanation as per the hints provided

 Selecting random element from PHP associative array – defining a Associative array

We define a php associative array named ‘guest’ that stores the name of the guest and the gender

Selecting random element from PHP associative array – randomly loading a element from the associative array

We make use of “array_name()” function that takes the array name as parameter to load one record randomly from the array. We store the guest name  and in php variable “guestName” and guest gender in a variable “guestGender”. We print the name and gender using the php ‘echo’ statement for testing.

Selecting random element from PHP associative array – checking the gender using if/else statement

Here we check the guest gender using the php if/else statement and greet the guest depending on the gender.

One thought on “Selecting random element from PHP associative array”

  1. Pingback: Greet the guests

Comments are closed.