0

I have code like below

<?php
if(true){
  global $search;
  $search = "hello";
}
elseif(true)
{
echo $search;
}
?>

I am unable to access $search value from if() block to elseif() block, is my approach is wrong? please anyone tell me any other way to access variables from one block to another, i need to write $search variable in if() block not like below

<?php
$search = "hello";// I don't want to use like this, 
if()
elseif()
?>
2
Contributors
1
Reply
22
Views
2 Years
Discussion Span
Last Post by bnmng
1

Hi.

I'm not really sure what you're trying to do. Your code above says, "If true then search $equals "hello", and if true then echo $search.

Either the if or the else runs, but not both. In this case, the if will run and $search will be set to "Hello", but even if the elseif is true, it won't run because the if already ran.

Also, it doesn't make sense that both the if and the else test for the save value, and it doesn't make sense that they're both testing true. You probably want to test against some variable that may be true or may be false.

Finally, you don't need global here, unless this is part of a function that isn't shown in this code snippet. But you have to define $search before the if block if you want it to be in the else block.

Maybe you want something like this.

<?php

$search=''; 

if(/*something*/) {
    $trueorfalse=true;
}
else {
    $trueorfalse=false;
}

if($trueorfalse=="true){
  $search = "hello";
}
else  
{
  $search = "goodbye";
}

echo $search;

?>
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.