Combining strings and numbers in PHP for a loop

Php newbie here

Can someone please tell me what is wrong with the syntax below. I have a maximum of 4 files - $ created_page1, $ created_page2, each of which has a corresponding title, etc. And I would like to process them in a loop. However, PHP throws shaky every time I try to concatenate a string and a loop number - in particular, $ created_page. $ Num_pages does not send the function $ created_page1 or $ created_page2 to the function, but simply converts the string and number to an integer. I am very sure, but I would be very grateful for any help or a more pleasant 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);    
}
+3
source share
3 answers

:

${'created_page'.$num_pages}

, , .

$created_page $num_pages .

, page_title

${'page_title'.$num_pages}
+1

:

$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);
}

PHP strval-

0

I think you want variables $created_page1; $created_page2, $created_page3, but php probably throws a notification that $created_pagedoesn't exist.

You need to use variable variables (is that what they are 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 $$, it first evaluates the variable $createdVar, which turns into created_page1, and then evaluates created_page1as if you typed$created_page1

0
source

All Articles