ob_start() within a loop - php

I've got a problem when looping using foreach() loop and inside of this loop using ob_start() and ob_get_clean().
Here's my function:
protected function renderEmail() {
$template = $this->_case.".php";
if(is_file($this->_dir.DS.$template)) {
ob_start();
if(!empty($this->_records)) {
foreach($this->_records as $key => $value) {
${$key} = $value;
}
}
require_once($this->_dir.DS.$template);
return ob_get_clean();
} else {
$this->_errors[] = "Email template not found";
return false;
} }
This function is basically generating content of the email and then returns it.
The problem I have is when I loop through a number of email addresses - to send the same email content - only the first one returns the content - the following ones are blank - any idea why?

Ok - you won't believe - once I've posted this question - straight after I've realised where the problem was - I'm using require_once() function - which prevents the same file to be included again - once changed to include() everything works fine!

Every time you are going to use a same file several times inside a loop, you should never user require_once() or include_once, instead use, 'include', and everything will be fine!

Why looping?
extract($this->_records);
looks a bit shorter than
foreach($this->_records as $key => $value) {
${$key} = $value;
}
and native in addition
and var_dump is a great help sometimes (for the next time you run into trouble like this one) :)

Related

Why is my PHP class method returning nothing when I try to use values taken from using preg_replace inside foreach without giving errors?

I'm trying to build an array with a few variations of some data, when using preg_replace and echoing out values, it works like normal, but if I try to store those values in an array, the function simply returns nothing, and gives no error.
Here's a piece of the code I'm using, it's inside a class.
$actions = array();
foreach($controllers as $ck => $cv) {
$cvar = 'br'.$ck.'actions';
foreach(self::$$cvar as $key => $value) {
if ($key != $value) {
$actions[$value] = $key;
if( preg_match('/[A-Z]/',$key)!==0 || preg_match('/[A-Z]/',$value)!==0 )
{
$key2=strtolower(preg_replace('/(?<=\\w)([A-Z])/','-\\1',$key));
$value2=strtolower(preg_replace('/(?<=\\w)([A-Z])/','-\\1',$value));
$actions[$value2] = $key2; // Everything works except for this line, if I comment it, it works, if I don't, it simply doesn't return even an error.
}
}
}
}
return $actions;
What is causing this weird behaviour? It should be able to add to the array like normal, but it doesn't...
So, I found out what was the problem:
In the arrays of values being used to create the $actions array (The $br(controller)actions array) there were some values that accidentally had some diacritics on them (Like the word "Demonstração"), which when going through the preg_replace function, became some of those black question mark boxes (�� Replacement Characters), which then were fed as array keys by the function and somehow made the function return empty instead of the array. Printing the values showed that the function still ran through all the loop iterations, but the array simply didn't return properly with those values on it.
I fixed it by removing the diacritics, then the method ran smooth as it should.

PHP avoid putting value in array

So lets say I have this line in my php script:
array_push($arr,array($a,$b,$c));
Lets say sometimes I have a $b1 variable to put in this array
I would like to not have duplicate for the sake of maintenance how can I avoid doing this:
```
if(!isset($b1)){
array_push($arr,array($a,$b,$c,$d));
}
else{
array_push($arr,array($a,$b,$b1,$c,$d));
}
```
This is the solution I have came up with
I was hoping for some kind of syntax trick I did not know about.
I believe this works the same as Marko Mackic's solution but without using # to suppress errors, however if there was a actual need to have null values in the array this is not a solution.
function skipNull($in){
$out=array();
foreach($in as $val){
if($val!==null){
array_push($out,$val);
}
}
return $out;
}
//skip part where variable are defined
array_push($arr,skipNull(array(
$a,$b,
isset($b1)?$b1:null,
$c,$d
)));

PHP array not working, multiple

Here's my code:
function prepare_machine($variables)
{
foreach ($variables AS $varname => $vartype)
{
if (isset($_REQUEST[$varname]))
{
$value = $_REQUEST[$varname];
return do_clean($value, $vartype);
}
else
exit;
}
}
It is called like this:
prepare_machine(array('order_by_time' => TYPE_BOOLEAN));
it all works fine, but if you have multiple things in the array, for examples;
prepare_machine(array('order_by_time' => TYPE_BOOLEAN, 'order_by_date' => TYPE_BOOLEAN));
it will only do anything with the first one.
Can anybody see what is wrong with my code?
Thanks
You're doing a return ... when you find a match in your inner loop. That's why it only processes one.
Also, you should be using array_key_exists($varname, $_REQUEST) because isset($_REQUEST[$varname]) will fail if $_REQUEST[$varname] is null.
return returns whatever you give it, and exits the function. You need to change your function somehow so that it only returns after processing all the variables.

basic PHP variable local/global issue

I have come from a background of C++ and am relatively new into the world of PHP.
I'm currently writing a little piece that has an index.php and definitions.php.
In definitions I have the variable
$passfile = "../ass1_data/passwords.txt";
I want to use $passfile inside a function in my index.
Can I just use it $passfile or do I have to use global with it as well?
This is what I have
function checkPasswd($login,$passwd){
global $passfile;
$p = $passfile;
foreach ($p as $line) {
// some code
}
}
At the moment I am getting the error 'Invalid argument supplied for foreach()'
Any help or explanations would be appreciated, thank you.
Assuming the text file contains lines with passwords in it you need to read the contents of the file in first and then loop through the results:
$passfile= file('../ass1_data/passwords.txt');
function checkPasswd($login,$passwd){
global $passfile;
foreach ($passfile as $line) {
// some code
}
}
1- you have to use global keyword for using global variable inside functions.
2- for second case(foreach) first you have to read the file, then use explode function to split it and use it in foreach.:
$passfile = "../ass1_data/passwords.txt";
function checkPasswd($login,$passwd){
global $passfile;
$p = explode("\n",file_get_contents($passfile));
foreach ($p as $line) {
// some code
}
}
You can't simply foreach over a string (even though you can access its bytes with subscript notation).
You need to turn it into an array first, one option for doing that is explode("\n").
However, it sounds like you want to open the file at that location. In that case, you can use file(), which will automatically provide you with an array of lines in that file.

Invalid argument foreach()

I have the follow code, but, i get an error in my code.
I cant find the problem but, I think it comes from:
UserManagement::findByUsername($username);
$a_allSections = UserManagement::findByUsername($username);
if($a_allSections)
{
foreach($a_allSections as $a_section)
{
echo $a_section['name'];?>
}
}
else
{
echo 'There's nothing found.' . "\n";
}
Evidently $a_allSections is not an array, so foreach complains. Use var_dump($a_allSections) to find out what exactly it is, and fix your code accordingly.
Check this way
UserManagement::findByUsername($username);
1.the function findByUsername($username) should return some values
2.the class should be included in current document.
3.Check whether your return result as array. if array means check is_array();
4.if above 3 ok in your question then you will not get the error.
$a_allSections may be empty
change condition to
if(is_array($a_allSections)){
...
}
to prevent such error on empty arrays

Categories