Aiden Ryan
Aiden Ryan

Reputation: 845

Selecting a random character froma string in PHP

I'm creating a security system in PHP which requires the user to enter a certain character from their unique security key, I was wondering how it is possible to make php return a selected character from a string.

For example, the security code is 1234567, I want php to randomly select 1 character from this string, and then compare that character to the character asked for in the security process

$number = rand(1,7); // The number = 7

E.G, please enter the 7th character of your security code.

//script to return the 7th character in the string and compare it to the entered character.

Thanks in advance :)

Upvotes: 1

Views: 398

Answers (2)

deceze
deceze

Reputation: 522085

$randomIndex = mt_rand(0, strlen($securityCode) - 1);
$randomChar = $securityCode[$randomIndex];

This creates a random number (mt_rand) between 0 and the last index of your string (strlen($securityCode) - 1). If your string is 10 characters long, that's a number between 0 and 9. It then takes the character at that index.

Upvotes: 4

shernshiou
shernshiou

Reputation: 518

Try substr, strlen and rand

$numbers = rand(0,strlen($securitycode) - 1);
$randChar = substr($securitycode, $numbers, 1);

Then compare..

Upvotes: 0

Related Questions