William
William

Reputation: 1069

Do a OR in PHP Variable?

I seen it around and not sure if it was in JS or PHP but if it was possible in PHP that would be great! If not, how would i go about it without a IF, if not possible without one then how do i go about it with one?

Code:

$myvar = str_replace("hello","jpg",$myvar) || str_replace("hello","gif",$myvar); //Didnt work

And i tried:

$myvar = (str_replace("hello","jpg",$myvar) || str_replace("hello","gif",$myvar)); //Didnt work

Basically what i am trying to achieve here is to run whatever one that comes back true. If it cant do: str_replace("hello","jpg",$myvar) then do str_replace("hi","gif",$myvar). Now i tried doing a IF but that also didnt work.

My IF that also didnt work:

if (str_replace("hello","jpg",$myvar) == true)
{
    $myvar = str_replace("hello","jpg",$myvar);
}
else if (str_replace("hello","gif",$myvar) == true)
{
    $myvar = str_replace("hello","gif",$myvar);
}

Upvotes: 0

Views: 57

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78994

Or just use an array:

$myvar = str_replace(array('hello', 'hi'), array('jpg', 'gif'), $myvar);

Upvotes: 0

Ghostff
Ghostff

Reputation: 1458

$myvar = (strpos($myvar, 'hello') !== false) ? str_replace('hello', 'jpg', $myvar) : str_replace('hi', 'gif', $myvar);

OR

if (strpos($myvar, 'hello') !== false)
{
     $myvar = str_replace('hello', 'jpg', $myvar);
}
elseif (strpos($myvar, 'hi') !== false)
{
     $myvar = str_replace('hi', 'gif', $myvar);
}

Upvotes: 2

u_mulder
u_mulder

Reputation: 54841

Simple solution is:

// if you have `hello` in a string - replace it
if (strpos($myvar, 'hello') !== false) {
    $myvar = str_replace("hello","jpg",$myvar);
} else {
    // else replace `hi`, 
    // if there's no `hi` in a string - it doesn't matter
    $myvar = str_replace("hi","gif",$myvar);
}

Upvotes: 3

Related Questions