Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter PHP - How to randomly select a language class message?

The idea here is to have a series of tips in application/language/english/tips_lang.php

$lang['tip1'] = 'Water your plants';
$lang['tip2'] = 'Aerate your soil';
$lang['tip3'] = 'Use ventilation';
$lang['tip4'] = 'Fertilizers are good';

etc...

In my controller I would like to have something like this pseudo-code

$input = $this->lang->line('tip_array');

$tip = array_rand($input, 1);

Anyone know if this is possible?

Thanks for giving a hand!

UPDATE controller

        //Random Tip
        $array = explode('|', $this->lang->line('tips'));
        $tips = array_rand($array, 1);
        $this->template->write('tips', $tips);
like image 660
pepe Avatar asked Jun 24 '26 04:06

pepe


1 Answers

CodeIgniter doesn't support n-dimensional arrays for the language files, but you can work around that:

$lang['tips'] = 'Water your plants|Aerate your soil|Use ventilation|Fertilizers are good';

Or, if you preffer to have them one on each line:

$lang['tips'] = array();
$lang['tips'][] = 'Water your plants';
$lang['tips'][] = 'Aerate your soil';
$lang['tips'][] = 'Use ventilation';
$lang['tips'][] = 'Fertilizers are good';
$lang['tips'] = implode('|', $lang['tips']);

/controllers/yourController.php:

$tips = explode('|', $this->lang->line('tips'));

echo $tips[array_rand($tips, 1)];

Hope it helps!

like image 157
Alix Axel Avatar answered Jun 25 '26 21:06

Alix Axel



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!