Wilson
Wilson

Reputation: 67

PHP - Square Brackets Before Functions

I use array_rand function to get random arrays value. after searching i found this code :

$random = $arList[array_rand($arList)];

My questions: Why use Square brackets before array_rand function? and when should we use it in our code?

[array_rand($arList)]

Upvotes: 0

Views: 76

Answers (1)

Ifenna Ozoekwe-Awagu
Ifenna Ozoekwe-Awagu

Reputation: 53

The square brackets don't have anything to with the array_rand() function. The code

$random = $arList[array_rand($arList)];

can be rewritten as

$randomIndex = array_rand($arList); $random = $arList[$randomIndex];

The code basically gets a random index and passes the value of that index to the $random variable. The square brackets are PHP array syntax to represent a particular index in the array.

The first value of $arList would be $arList[0] (it starts counting from 0). The second would be $arList[1] and so on. So, as I mentioned before, array_rand doesn't have anything to do with the square brackets.

You can find out more about arrays in PHP here.

Upvotes: 2

Related Questions