Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the first, second, third etc numbers of an array

Tags:

arrays

php

I've started learning about arrays and they've very confusing. I want to generate 4 numbers using this:

$numbers = range(1,4);

Then I shuffle with this:

shuffle($numbers);

Now I want to get each number as a variable, I've been told the best way is arrays. I have this code:

foreach($numbers as $number){

$test = array("first"=>"$number");
echo $test['first'];

}

What this does is echo all 4 numbers together, like "3142" or "3241" etc. Which is close to what I want, but I need all 4 numbers to have their own variable each. So I made this:

foreach($numbers as $number){

$test =     array("first"=>"$number","second"=>"$number","third"=>"$number","fourth"=>"$number");
echo $test['first']," ",$test['second']," ",$test['third']," ",$test['fourth'],"     <br>";

}

This just echoes the 4 numbers 4 times. I need "first" to be the first number, "second" to be the second number of the 4 and the same for the third and fourth. I've been searching the web but don't know specifically what to search for to find the answer.

If someone answers could they please put as much detail into what certain functions do as possible, I want to learn not just get working code :)

like image 402
Ben Avatar asked Jan 29 '26 12:01

Ben


1 Answers

You can use sizeof() it is return size of array size, and pass the key value manually. Like- echo $numbers[0]; echo $numbers[1]; echo $numbers[2];

like image 56
er.irfankhan11 Avatar answered Feb 01 '26 00:02

er.irfankhan11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!