简体   繁体   中英

How do i turn an string into variables and still get a good output

How do i turn an string into variables and still get a good output.

$text = "showandreturn";

$disp = str_split($text, 2); 

$firstnum = 3;

for($b = 0; $b<$firstnum; $b++){

    $a = "$disp[$b]"; #showan

}

$b = "ENDED";

for($b = $firstnum; $b<sizeof($disp); $b++){

    $c = "$disp[$b]"; #dreturn

    echo = "$a$b$c";
}

my current output with this code is . andranetanurann .. And I want beter result like showanENDEDdreturn

Thanks for your time and understanding..

Are you trying to put ENDED in the middle of the string?
In that case have a look at this:

$text = "showandreturn";
$b = "ENDED";

$len = strlen($text); // lenght of string
// Output half string + $b + rest of string
Echo substr($text, 0, floor($len/2)) . $b . substr($text, floor($len/2));

https://3v4l.org/Ea6tn

Alternative 1

What you need is variables variable

$foo = 'bar';
$foo = 'magic';

echo $foo; //Outputs magic

Alternative 2:

you can check http://php.net/manual/en/function.parse-str.php

parse_str($"My Value=Something");
echo $My_Value; // Something

Alternative 3:

echo eval('return $'. $string . ';');

You are overwriting your variables every time it loops so only the result of the last loop is stored in the variable.

This code should return the required output.

$text = "showandreturn";
$disp = str_split($text, 2);
$num = 3;
$a = '';
$c = '';
for($b = 0; $b<$num; $b++){
    $a .= $disp[$b];
}
$b = "ENDED";
for($bn = $num; $bn<sizeof($disp); $bn++){
    $c .= $disp[$bn];
}
echo $a.$b.$c;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM