lyhong
lyhong

Reputation: 947

PHP print text randomly once inside a loop

I have data selected from database in object format. I want to loop it but I also include text randomly to the display. How to add that text to a random place in object? or how to print it randomly once inside the loop?

//Object data

$obj = (object) [

'0' => ['name' => 'Banana'],

'1' => ['name' => 'Potato'],

'2' => ['name' => 'Mango']

];

//addition text will be displayed

$text = 'My random text';

foreach($obj as $d) {

 echo $d->name; 

}

Result can be

Or

Or

...

Upvotes: 0

Views: 401

Answers (4)

Md. Samsull Arefeen
Md. Samsull Arefeen

Reputation: 61

May be you are looking for this ..

foreach($obj as $d) {

 $d->name = $d->name . " " . $text;  // This concates the text.
 echo $d->name; 

}

Upvotes: 0

Vikash Kumar
Vikash Kumar

Reputation: 1111

Just find the a random position index from your object data like this.

$randPos = rand(0, count($obj)-1);

And put your random text right after this random index of object data while accessing it through look.

//addition text will be displayed

$text = 'My random text';

foreach($obj as $k => $d) {
   echo $d->name; 
   if($k == $randPos) echo $text;
}

Hope this will help to solve your query !!

Upvotes: 1

ThrowBackDewd
ThrowBackDewd

Reputation: 1767

I would use a random number. See http://php.net/manual/en/function.rand.php

$rand = rand(0, count($yourArray));

Then within your array loop, test the key value of the given item compared to your random number if it matches, echo your text.

Upvotes: 1

Marcin N.
Marcin N.

Reputation: 68

Do you have a way of determining how many arrays are stored in your Object?

If so, generate a random number between 0 and $numArraysInObject - 1 and use a good ol' for ($i = 0; $i < $numArraysInObject; $i++). When $i matches $numArraysInObject, print your random text.

$printTime = rand(0, $numArraysInObject);
for ($i = 0; $i < $numArraysInObject; $i++) {
    if ($i == $printTime)
        echo "My random text";
    echo $d -> name;
}

Upvotes: 0

Related Questions