Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call random Function in PHP

So I have this functions, I was wondering how can I call the two function randomly. I mean, the php code will randomly select from the two? how can I do that?

Example Functions

    function one() {
        echo '
<div id="two-post">
    <a href="<?php the_permalink(); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>">
        <?php the_post_thumbnail('dos'); ?>

        <div class="entry-meta">
            <h1><?php the_title(); ?></h1>
            <p>By <?php the_author(); ?></p>
        </div>

        <div class="overlay2"></div>
    </a>
</div>

';
    }

    function two() {
        echo '<div class="two">' . wp_trim_words( get_the_content(), 50, '' ) . '</div>';
    }

    function three() { // function names without "-"
        echo '<div class="third">' . the_author() .'</div>';
    }

The code for selecting the two functions randomly

<?php

$functions = array('one', 'two', 'three'); // remove the open and close parenthesis () in the strings

call_user_func($functions[array_rand($functions)]);

?>

The code above doesn't work. Was wonder if someone could help?

like image 652
Kareen Lagasca Avatar asked Dec 14 '22 20:12

Kareen Lagasca


2 Answers

You can call it something like this:

function one() {
    echo '
        <div id="two-post">
            <a href="' . the_permalink() .'" alt="' . the_title() .'" title="' . the_title() .'">
                ' . the_post_thumbnail('dos') . '

                <div class="entry-meta">
                    <h1>' . the_title() . '</h1>
                    <p>By ' . the_author() . '</p>
                </div>

                <div class="overlay2"></div>
            </a>
        </div>
    ';
}

function two() {
    echo wp_trim_words( get_the_content(), 50, '' );
}

function three() { // function names without "-"
    echo '<div>' . the_author() .'</div>';
}

$functions = array('one', 'two', 'three'); // remove the open and close parenthesis () in the strings

$functions[array_rand($functions)](); // call it!

// or
call_user_func($functions[array_rand($functions)]);
like image 86
Kevin Avatar answered Dec 31 '22 21:12

Kevin


You can use Switch case here...

function one(){
             //some code;
             }
function two(){
             //some code;
             }
function random_caller(){
          int x = rand(0,1);
          switch(x){
          case 1: one();
          break;
          case 2: two();
          break;
          default: echo "could not run any function";
          break;
            }
            }
like image 36
Manmohan Jangid Avatar answered Dec 31 '22 21:12

Manmohan Jangid