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()
?>

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;

?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.