John Davidson

php - Pulling random object out of array of objects

0 comments
Message:


I have an array of objects and I'm trying to pull a random object out of it, but all I get is id of a single object.


$arrayOfItems = [];

foreach($boxItems as $item)
{
if($item->getMainImage() != null)
{
array_push($arrayOfItems, $item);
}
}

if(count($arrayOfItems)==0)
{
$this->fail("Theres no items with images");
}

$randomItem = array_rand($arrayOfItems,1);

Am I doing something wrong or does the array_rand just doesn't have that functionality?



My Answer:
You are close, but the issue is with how you are using the array_rand function. The array_rand function returns a random key from the array, not the actual object itself. To get the random object from the array, you can use the random key to access the object in the array.

Here is how you can modify your code to get a random object from the array:

php
$arrayOfItems = [];

foreach($boxItems as $item)
{
if($item->getMainImage() != null)
{
array_push($arrayOfItems, $item);
}
}

if(count($arrayOfItems)==0)
{
$this->fail("Theres no items with images");
}

$randomKey = array_rand($arrayOfItems);
$randomItem = $arrayOfItems[$randomKey];


Now, $randomItem will contain a random object from the $arrayOfItems array.

Rate this post

3 of 5 based on 9520 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us