在两个PHP函数之间随机切换

在两个PHP函数之间随机切换,php,random,Php,Random,我在一个网页上有两个PHP函数。我想随机运行这两个函数中的一个。我知道如何使用PHP处理divs或HTML,但不知道如何随机运行PHP函数。我想使用PHP而不是Javascript 以下是我的两个功能: <?php get_template_part('module_sidebar_1'); ?> <?php get_template_part('module_sidebar_2'); ?> 用于在末尾生成数字 <?php get_template_part('

我在一个网页上有两个PHP函数。我想随机运行这两个函数中的一个。我知道如何使用PHP处理
div
s或HTML,但不知道如何随机运行PHP函数。我想使用PHP而不是Javascript

以下是我的两个功能:

<?php get_template_part('module_sidebar_1'); ?>
<?php get_template_part('module_sidebar_2'); ?>

用于在末尾生成数字

<?php get_template_part('module_sidebar_'.mt_rand(1,2)); ?>
用于在末尾生成数字

<?php get_template_part('module_sidebar_'.mt_rand(1,2)); ?>

像这样的怎么样

$random = rand(0,1);
if ($random == 0){
    get_template_part('module_sidebar_1');
}
else{
    get_template_part('module_sidebar_2');
}

像这样的怎么样

$random = rand(0,1);
if ($random == 0){
    get_template_part('module_sidebar_1');
}
else{
    get_template_part('module_sidebar_2');
}
如果您还有混合(数字+非数字)模板名称, 创建一个包含所有模板名称的数组,如

$templates = ['module_sidebar_1','module_sidebar_2','module_sidebar_non_numeric'];
并调用随机模板文件

<?php get_template_part($templates[array_rand($templates)])?>

如果您还有混合(数字+非数字)模板名称, 创建一个包含所有模板名称的数组,如

$templates = ['module_sidebar_1','module_sidebar_2','module_sidebar_non_numeric'];
并调用随机模板文件

<?php get_template_part($templates[array_rand($templates)])?>


谢谢,这是一个很好的方法,但它只适用于数值吗?我的意思是我使用了1和2作为例子,但真正的名字是module_sidebar_sondage和module_sidebar_bon_plan。它是否适用于@mmdwc?我已经更新了我的答案,向您展示了如何使用单词而不是数字。谢谢,这是一个很好的方法,但它是否只适用于数值?我的意思是我使用了1和2作为例子,但真正的名字是module_sidebar_sondage和module_sidebar_bon_plan。我已经更新了我的答案,告诉你如何使用单词而不是数字。谢谢@Pavel Němec我刚刚在第2行随机添加了一个$,效果非常好,非常感谢!谢谢@Pavel Němec我刚刚在第2行随机添加了$before,效果非常好,非常感谢!