rookieloops
rookieloops

Reputation: 47

Combining strings and numbers in PHP for loop

PHP newbie here

Can anyone please tell me what is wrong with the below syntax. I have a maximum of 4 files - $created_page1, $created_page2 each with a corresponding page title etc and would like to process these in a loop. However PHP throws a wobbly every time I try to concatenate the string and loop number - specifically $created_page.$num_pages doesn't result in sending $created_page1 or $created_page2 to the function, instead it just converts the string and number to an integer. Very basic I am sure but I would be very grateful for any help or a nicer solution that I can easily understand. Thanks in advance!

$addit_pages == 4;

for ($num_pages=1;$num_pages<=$addit_pages ;$num_pages++) { 

replaceFileContent   ($dir,$created_page.$num_pages,"*page_title*",$page_title.$num_pages); 
//replaceFileContent  ($dir,$created_page2,"*page_title*",$page_title2); 
//replaceFileContent  ($dir,$created_page1,"*page_title*",$page_title3); 
//replaceFileContent  ($dir,$created_page3,"*page_title*",$page_title4);    
}

Upvotes: 4

Views: 354

Answers (3)

domvoyt
domvoyt

Reputation: 416

Your code to get the variable name should be:

${'created_page'.$num_pages}

This is because you have to evaluate the string inside the braces before you attempt to access the variable.

Your previous code was trying to access the variables $created_page and $num_pages, and simply concatenate their values into a string.

Of course, the same goes for the page_title variable

${'page_title'.$num_pages}

Upvotes: 1

aknosis
aknosis

Reputation: 4308

I think what you are asking is you want the variables $created_page1; $created_page2, $created_page3 but php is probably throwing a notice that $created_page doesn't exist.

You need to use variable variables (is this what they're called?)

$addit_pages == 4;

for ($num_pages=1;$num_pages<=$addit_pages ;$num_pages++) { 
    $createdVar = 'created_page'.$num_pages;
    $titleVar = 'page_title'.$num_pages;
    replaceFileContent   ($dir,$$createdVar,"*page_title*",$$titleVar); 
}

When you use $$ this first evaluates the variable $createdVar turns that into created_page1 and then evaluates created_page1 as if you had typed in $created_page1

Upvotes: 0

Wampie Driessen
Wampie Driessen

Reputation: 1710

you could try this:

$addit_pages == 4;

for ($num_pages=1;$num_pages<=$addit_pages ;$num_pages++) {

replaceFileContent ($dir,$created_page.strval($num_pages),"*page_title*",$page_title.strval($num_pages)); //replaceFileContent ($dir,$created_page2,"*page_title*",$page_title2); //replaceFileContent ($dir,$created_page1,"*page_title*",$page_title3); //replaceFileContent ($dir,$created_page3,"*page_title*",$page_title4);
}

the PHP strval function makes any integer into a string

Upvotes: 0

Related Questions