0

I want to create a simple php function to return an array of variable in wordpress template.

php function in function.php:

function testme (){
     $color = 'imaginary'; // or real  
     $y = 'yellow';
     $s = 'silver' ;

     if ($color != 'imaginary') {
            $y = 'golden';
            $s = 'silver' ;
     } else {
            $y = 'yellow';
            $s = 'white' ;
     }

     $wall = array();
     $wall = array ($y ,$s);
     return $wall;
}

Called this function in my template like this:

<?php 

testme();

?>

<h1>TOP STRIP COLOR IS <?php echo $wall['0'] ?></h1>
<h2>BOTTOM STRIP  COLOR IS <?php echo $wall['1'] ?></h2>

But I am not getting array of values in my <h1> and <h2> tags. Help me to point out my mistake.

2
  • 1
    The syntax highlighter shows your error. You're missing a quote: $s = 'silver ; <-- here Commented Mar 23, 2014 at 17:12
  • 2
    Assign the returned value to a variable: $wall = testme(); Commented Mar 23, 2014 at 17:12

2 Answers 2

2

You need to put the return value of the function into variables. Like this:

$wall = testme();

and then use it:

<h1>TOP STRIP COLOR IS <?php echo $wall['0'] ?></h1>
<h2>BOTTOM STRIP  COLOR IS <?php echo $wall['1'] ?></h2>

The $wall variables you placed inside the testme function will only work inside the scope of the function.

Sign up to request clarification or add additional context in comments.

Comments

1

Modify testme() function to something like this (I removed unused lines and move $color to function arguments):

function testme ($color) {
    if ($color != 'imaginary') {
        $y = 'golden';
        $s = 'silver';
    } else {
        $y = 'yellow';
        $s = 'white';
    }

    return array($y, $s);
}

And, as said in top comments, assign return value to variable and use it:

<?php
    $result = testme('imaginary'); // Here we pass argument to function
?>
<h1>TOP STRIP COLOR IS <?php echo $result[0] ?></h1>
<h2>BOTTOM STRIP  COLOR IS <?php echo $result[1] ?></h2>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.