I have an array structure of 60 elements. I'd like to use a for/foreach/while to read this structure.
This is what I have :
$this->details->field_link_01[0]['title']
$this->details->field_link_02[0]['title']
..
$this->details->field_link_60[0]['title']
And what i need is the following.
$myvar = eval ( "$this->details->field_link_" . $cont . "[0]['title']" )
What I have seen is PHP let to use $ as evaluation function
$myvar = ${"this->details->field_link_" . $cont . "[0]['title']" }
But it didn't work.
Is there any other solution ? Which PHP version ? 5.2 , 5.6 , 7 ?
Have a look at Variable variables and sprintf.
for ($i = 1; $i <= 60; $i++) {
$fieldName = sprintf("field_link_%02d", $i);
$fieldLink = $this->details->$fieldName;
$myvar = $fieldLink[0]['title'];
echo $myvar;
}
Related
define('HOUSEHOLD_CHILD1','custom_16');
define('HOUSEHOLD_CHILD2','custom_14');
define('HOUSEHOLD_CHILD3','custom_13');
define('HOUSEHOLD_CHILD4','custom_12');
function household_function() {
$vari = array();
$var['household'][HOUSEHOLD_CHILD1] = $_SESSION['household_membership'][1];
$var['household'][HOUSEHOLD_CHILD2] = $_SESSION['household_membership'][2];
$var['household'][HOUSEHOLD_CHILD3] = $_SESSION['household_membership'][3];
}
I want to implement the above code in foreach loop
like something similar to concatenate.
it should be something similar to this
foreach($_SESSION['household'] as $key => $value) {
$var['household'][HOUSEHOLD_CHILDi] = [i];//i need to concatenate the constant
//to something similar we do for string
}
The constant function will serve your purpose:
define('HOUSEHOLD_CHILD1','custom_16');
define('HOUSEHOLD_CHILD2','custom_14');
define('HOUSEHOLD_CHILD3','custom_13');
define('HOUSEHOLD_CHILD4','custom_12');
for($i = 1; $i <= 4; $i++){
print(constant("HOUSEHOLD_CHILD".$i).PHP_EOL);
}
The output of the given code will be:
custom_16
custom_14
custom_13
custom_12
DEMO
I have a php file that was given to me by a company that produces online coupons. The file is supposed to generate a dynamic url and then redirect you to that page. All they told me i needed to do was to create an echo call at the bottom. The $cpt is the only thing that should be dynamically generated in the url so this is what I have and it is not working properly.
<?php
//Generate cipher
function EncodeCPT($pinCode, $offerCode, $shortKey, $longKey){
$decodeX = " abcdefghijklmnopqrstuvwxyz0123456789!$%()*+,-.#;<=>?[]^_{|}~";
$encodeModulo = array_fill(0, 256, 0);
$vob[0] = $offerCode % 100;
$vob[1] = (($offerCode - $vob[0]) / 100) % 100;
for ($i = 0; $i < 61; $i++)
$encodeModulo[substr($decodeX, $i, 1)] = $i;
$pinCode = strtolower($pinCode) . strval($offerCode);
if (strlen($pinCode) < 20){
$pinCode .= ' couponsincproduction';
$pinCode = substr($pinCode, 0, 20);
}
//$checkCode = "LC";
//$pinCode = "LC10";
//$offerCode = "115694";
//$shortKey = "6oigl3qf5e";
//$longKey = "Lm9A7w8tjpUCaoMidGFSYXrHZnyDRKhlTbk1Oz4f5QBsqveEWuxg6PNV2cJ3I";
$q = 0;
$j = strlen($pinCode);
$k = strlen($shortKey);
$s1 = $s2 = $s3 = null;
$cpt = '';
for ($i = 0; $i < $j; $i++){
$s1 = $encodeModulo[substr($pinCode, $i, 1)];
$s2 = 2 * $encodeModulo[substr($shortKey, $i % $k, 1)];
$s3 = $vob[$i % 2];
$q = ($q + $s1 + $s2 + $s3) % 61;
$cpt .= substr($longKey, $q, 1);
}
return $cpt;
}
echo("http://bricks.coupons.com/enable.asp?0=115694&c=LC&p=LC10&" .$cpt);
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=http://bricks.coupons.com /enable.asp?0=115694&c=LC&p=LC10&"($cpt)">';
?>
I have tried a couple things but nothing seems to be working. Does any one have any ideas? Thank you in advance.
Just use header()
Replace this
echo("http://bricks.coupons.com/enable.asp?0=115694&c=LC&p=LC10&" .$cpt);
with
$cpt = EncodeCPT("yourparameters");
header("location:http://bricks.coupons.com/enable.asp?0=115694&c=LC&p=LC10&$cpt");
In your code you’ve defined the function EncodeCPT but you’ve never actually called it. You may think of function definitions as separate from other parts of your script. Any variable used inside a function (unless used with the global keyword) has only a local scope. Therefore, the variables $pinCode, $offerCode, $shortKey, $longKey and $cpt don’t even exist outside the scope of your function (if in doubt, check it with isset). To make them exist, you have to do something like the following:
/* Change these values if necessary */
$pinCode = "LC10";
$offerCode = "115694";
$shortKey = "6oigl3qf5e";
$longKey = "Lm9A7w8tjpUCaoMidGFSYXrHZnyDRKhlTbk1Oz4f5QBsqveEWuxg6PNV2cJ3I";
/* Do not change after this line */
$cpt = EncodeCPT($pinCode, $offerCode, $shortKey, $longKey);
$url = "http://bricks.coupons.com/enable.asp?0=115694&c=LC&p=LC10&".$cpt;
In spite of having identical names, $pinCode, $offerCode, $shortKey, $longKey and $cpt are global variables in the code above. To avoid confusion, you may use different names like $a, $b, $c, $d, $e or any valid variable names of your choice. For a clearer understanding of the matter, read more about variable scope from the PHP manual.
Now comes the redirect part. If you want the script to redirect automatically:
header("location: $url");
On the other hand, if you want the user to click on a link for the redirect:
print("Click Here");
if you want to use the return value of the function EncodeCPT($pinCode, $offerCode, $shortKey, $longKey)
You need to find where this function is called and do something like this:
$cpt = EncodeCPT(parameter1,parameter2,parameter3,parameter4);
and at the end of the script you can then use $cpt, as mentioned by someone else.
header("location:http://bricks.coupons.com/enable.asp?0=115694&c=LC&p=LC10&$cpt");
I need to run over some pages written in PHP by somebody that doesn't know that a variable should be initialized before use..
Therefore I have thousands of lines to check in order to make sure I Do not have such thing
<?php
$foo = $bar . "I m a noob";
?>
and of course having the problem with $bar not initialized.
The problem is that I have about 20~50 variables in this case in 25 files..
Do you know any super-hero way to set all the variables to ' ' or null ?
I do not want to set the warning level to E or W .. that's too crappy.
Thanks in advance!
Theoretically this code at the beginning of the script does the job:
$code = file_get_contents(__FILE__);
preg_match_all('/(?<=\$)[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $code, $matches);
$variables = array_unique($matches[0]);
foreach ($variables as $variable) {
if (!isset($$variable)) {
$$variable = null;
}
}
The regular expression is from PHP site.
EDIT
A clean and quicker way, without a regular expression:
$code = file_get_contents(__FILE__);
$tokens = token_get_all($code);
foreach ($tokens as $token) {
if (is_array($token) && $token[0] == T_VARIABLE) {
$variable = ltrim($token[1], '$');
if (!isset($$variable)) {
$$variable = null;
}
}
}
you can use an array for the 25:
for ($i = 0; $i < 25; $i++) { $bar[$i] = ''; /* you can change the "" to null */ }
using an array with a for, you can set a great number of vars with diferente values, or with the same value.
At first glance I think you can get what I'm trying to do. I want to loop though variables with the same name but with a numerical prefix. I also had some confusion about the kind of loop I should use, not sure if a "for" loop would work. The only thing is I can't wrap my head around how php could interpret "on the fly" or fabricated variable. Ran into some trouble with outputting a string with a dollar sign as well. Thanks in advance!
$hello1 = "hello1";
$hello2 = "hello2";
$hello3 = "hello3";
$hello4 = "hello4";
$hello5 = "hello5";
$hello6 = "hello6";
$hello7 = "hello7";
$hello8 = "hello8";
$hello9 = "hello9";
$hello10 = "hello10";
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo $hello . $counter . "<br>";
}
It's generally frowned upon, since it makes code much harder to read and follow, but you can actually use one variable's value as another variable's name:
$foo = "bar";
$baz = "foo";
echo $$baz; // will print "bar"
$foofoo = "qux";
echo ${$baz . 'foo'}; // will print "qux"
For more info, see the PHP documentation on variable Variables.
However, as I already mentioned, this can lead to some very difficult-to-read code. Are you sure that you couldn't just use an array instead?
$hello = array(
"hello1",
"hello2",
// ... etc
);
foreach($hello as $item) {
echo $item . "<br>";
}
Try ${"hello" . $counter}
$a = "hell";
$b = "o";
$hello = "world";
echo ${$a . $b};
// output: world
You can use variable variables as:
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo ${'hello' . $counter } , '<br>';
}
as I guess u not even need to declare $hello1 = "hello1". coz the $counter is incrementing the numbers by its loop.
<?php
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo 'hello' . $counter . "\n";
}
?>
so this is enough to get the output as you want.
the output will be:-
hello1
hello2
hello3
hello4
hello5
hello6
hello7
etc...
So I have fields that are generated dynamically in a different page and then their results should posted to story.php page. fields is going to be : *noun1 *noun2 *noun3 and story is going to be : somebody is doing *noun1 etc. What I want to do is to replace *noun1 in the story with the *noun, I have posted from the previous page ( I have *noun1 posted from the previous page ) but the code below is not working :
$fields = $_POST['fields'];
$story = $_POST['story'];
$fieldsArray = split(' ', $fields);
for ($i = 0; $i < count($fieldsArray); $i++) {
${$fieldsArray[$i]} = $_POST[$fieldsArray[$i]];
}
// replace words in story with input
for ($i = 0; $i < count($story); $i++) {
$thisWord = $story[$i];
if ($thisWord[0] == '*')
$story[$i] = ${$thisWord.substring(1)};
}
$tokensArray = split(' ',$tokens);
echo $story;
Your problem is likely that you are trying to echo $story, which I gather is an array. You might have better luck with the following:
$storyString = '';
for ($i = 0; $i < count($story); $i++)
{
$storyString .= $story[i] . ' ';
}
echo $storyString;
echo can't print an array, but you can echo strings to your heart's content.
You almost certainly don't want variable variables (e.g. ${$fieldsArray[$i]}). Also, $thisWord.substring(1) looks like you're trying to invoke a method, but that's not what it does; . is for string concatenation. In PHP, strings aren't objects. Use the substr function to get a substring.
preg_replace_callback can replace all your code, but its use of higher order functions might be too much to get into right now. For example,
function sequence($arr) {
return function() {
static $i=0
$val = $arr[$i++];
$i %= count($arr);
return $val;
}
}
echo preg_replace_callback('/\*\w+/', sequence(array('Dog', 'man')), "*Man bites *dog.");
will produce "Dog bites man." Code sample requires PHP 5.3 for anonymous functions.