/    Sign up×
Community /Pin to ProfileBookmark

A part of a PHP code is a content of a string, solution

Hello. How can I convert content of a one line string into a code, that actually executes? Lets say that I intend to run the following code:

[code]
<?php

$sum=0;
for($i=1;$i<11;$i++){
$sum+=$i;
}

echo $sum;

?>
[/code]

but part of the code is a content of a string $s:

[code]
<?php

$sum=0;
$s=”for($i=1;$i<11;$i++){“;

//what to write here to use the content of the string $s as a code
$sum+=$i;
}

echo $sum;

?>
[/code]

Thank you.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@daveyerwinNov 25.2021 — > @codewitch#1639849 How can I convert content of a one line string into a code

where does this string come from ?

is it user input ?

https://www.php.net/manual/en/function.eval.php
Copy linkTweet thisAlerts:
@NogDogNov 25.2021 — You could do it with [u][eval()](https://php.net/eval)[/u], but be very, very careful: it's potentially a horrible security hole if anyone is able to manipulate what ends up in that string. As someone wise once said, "If eval() is the answer, you're probably asking the wrong question."
Copy linkTweet thisAlerts:
@NogDogNov 25.2021 — PS: If the intent is simply to be able to specify the bounds of that loop, I would use a couple variables rather than that entire string:
[code=php]
$start = 1;
$iterations = 10;
$sum = 0;
for($i = $start; $i < ($start + $iterations); $i++) {
$sum += $i;
}
echo $sum;
[/code]

Or, put all that into a function that you pass your iteration parameters to:
[code=php]
$start = 1;
$iterations = 10;
$sum = add_sequence($start, $iterations);
echo $sum;

function add_sequence($start, $end) {
$sum = 0;
for($i = $start; $i < ($start + $end); $i++) {
$sum += $i;
}
return $sum;
}
[/code]
×

Success!

Help @codewitch spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...