2

Is there a way, in PHP, to change which variable is being changed based on another factor. Example:

$str1 = "The string is 1";
$str2 = "The string is 2";
$str3 = "The string is 3";
$X = 3;
echo $strX;

>> "The string is 3."

Edit: Thanks that's exactly what I needed :)

1

2 Answers 2

5
<?php
$str1 = "The string is 1";
$str2 = "The string is 2";
$str3 = "The string is 3";
$X = 3;
echo ${"str".$X};
?>

read more here Variable variables

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

1 Comment

Little explanation will help to future visitors.
3

I think you are looking for

  $str1 = "The string is 1";
  $str2 = "The string is 2";
  $str3 = "The string is 3";
  $X = "str2";
  echo ${$X};

You could also use

   $str1 = "The string is 1";
   $str2 = "The string is 2";
   $str3 = "The string is 3";
   $X = "2";
   echo ${"str".$X};

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.