PHP Error: invalid argument supplied for foreach() - php

I'm trying to use this function at the bottom of a plugin's main PHP file to determine if one of its action hooks is being used by the tag specified. However, I'm getting a "Warning" on the 2nd foreach in the code below. Why is this? Is there a better way to see if a Wordpress action hook is being used?
<?php
function dump_hook($tag, $hook)
{
ksort($hook);
echo "<pre>>>>>>\t$tag<br>";
foreach ($hook as $priority => $functions) {
echo $priority;
foreach ($functions as $function) {
if ($function['function'] != 'list_hook_details') {
echo "\t";
if (is_string($function['function']))
echo $function['function'];
elseif (is_string($function['function'][0]))
echo $function['function'][0] . ' -> ' . $function['function'][1];
elseif (is_object($function['function'][0]))
echo "(object) " . get_class($function['function'][0]) . ' -> ' . $function['function'][1];
else
print_r($function);
echo ' (' . $function['accepted_args'] . ') <br>';
}
}
}
echo '</pre>';
}
$tag = array('anspress_loaded');
$hook = array('find_do_for_anspress');
dump_hook($tag, $hook);

Some errors from your code:
1.) $tag is array, but in your function it's used as string:
<?php
echo "<pre>>>>>>\t$tag<br>";
2.)$hook is array, so first foreach works ok:
<?php
// for first row
// $priority is int 0
// $functions is string find_do_for_anspress
foreach($hook as $priority => $functions ) {}
Next you try to do foreach with string $functions, but it's not iterrable, so php says to you aforementioned error.

Related

(novice) wrote 2 functions but getting error after error after error

I've been trying to get further in PHP and writing functions daily to practice but started to get the feeling I'm either overcomplicating or doing it completely wrong.
My 2 functions for this script:
function getFilesAndContent($path)
{
$data = [];
$folderContents = new DirectoryIterator($path);
foreach ($folderContents as $fileInfo) {
if ($fileInfo->isDot()) {
break;
}
$fileData = [
'file_name' => $fileInfo->getName(),
];
if ($fileInfo->getExtension()) {
$fileData['contents'] = getFileContents($fileInfo->getPathname());
}
$data = $fileData;
}
return $data;
}
function getFileContents($path)
{
$names = file_get_contents($fileInfo->getPathname());
$names = implode("\n", $names);
sort($names);
$contents = '';
foreach ($names as $name) {
$contents += $name . ' (' . strlen($name) . ')<br>';
}
return $name;
}
All I want to do is:
foreach (getFilesAndContent('.') as $data) {
echo $data['file_name'];
echo '<br>';
echo $data['contents'];
echo '<hr>';
The error:
FATAL ERROR Uncaught Error: Call to undefined method DirectoryIterator::getName() in /home4/phptest/public_html/code.php70(5) : eval()'d code:15 Stack trace: #0 /home4/phptest/public_html/code.php70(5) : eval()'d code(45): getFilesAndContent('.') #1 /home4/phptest/public_html/code.php70(5): eval() #2 {main} thrown on line number 15
The file it's supposed to read is a simple .txt files with a list of names, nothing more.
Any help appreciated! Also wondering if it's better to just rewrite the entire functions if I keep getting so many errors?
You have many things to fix in your code, for example changing undefined method getName() to something else, don't use break to skip because it will exit the loop, using explode(string $separator, string $string) to split string by separator, return $contents from getFileContents() function to return final concatenated string, etc.
I think, your goal is to display all *.txt files and its contents, with length for each line in contents. Try this:
$d = dir('.');
while (($file = $d->read()) !== false) { // iterate all files
if (preg_match('/\.txt$/', $file)) { // filter only file ends with .txt
$contents = explode("\n", file_get_contents($d->path . '/' . $file)); // get file contents, split by \n
array_walk($contents, function(&$item) {
$item .= ' (' . strlen($item) . ')';
}); // add (length) in the end of each line
// display it
echo '<strong>' . $file . '</strong><br>';
echo implode('<br>', $contents);
echo '<hr>';
}
}

Getting a random object from an array in PHP

First and foremost, forgive me if my language is off - I'm still learning how to both speak and write in programming languages. How I can retrieve an entire object from an array in PHP when that array has several key, value pairs?
<?php
$quotes = array();
$quotes[0] = array(
"quote" => "This is a great quote",
"attribution" => "Benjamin Franklin"
);
$quotes[1] = array(
"quote" => "This here is a really good quote",
"attribution" => "Theodore Roosevelt"
);
function get_random_quote($quote_id, $quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
} ?>
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
Using array_rand and var_dump I'm able to view the item in the browser in raw form, but I'm unable to actually figure out how to get each element to display in HTML.
$quote = $quotes;
$random_quote = array_rand($quote);
var_dump($quote[$random_quote]);
Thanks in advance for any help!
No need for that hefty function
$random=$quotes[array_rand($quotes)];
echo $random["quote"];
echo $random["attribution"];
Also, this is useless
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
If you have to run a loop over all the elements then why randomize hem in the first place? This is circular. You should just run the loop as many number of times as the quotes you need in output. If you however just need all the quotes but in a random order then that can simply be done in one line.
shuffle($quotes); // this will randomize your quotes order for loop
foreach($quotes as $qoute)
{
echo $quote["quote"];
echo $quote["attribution"];
}
This will also make sure that your quotes are not repeated, whereas your own solution and the other suggestions will still repeat your quotes randomly for any reasonably sized array of quotes.
A simpler version of your function would be
function get_random_quote(&$quotes)
{
$quote=$quotes[array_rand($quotes)];
return <<<HTML
<h1>{$quote["quote"]}</h1>
<p>{$quote["attribution"]}</p>
HTML;
}
function should be like this
function get_random_quote($quote_id, $quote) {
$m = 0;
$n = sizeof($quote)-1;
$i= rand($m, $n);
$output = "";
$output = '<h1>' . $quote[$i]["quote"] . '.</h1>';
$output .= '<p>' . $quote[$i]["attribution"] . '</p>';
return $output;
}
However you are not using your first parameter-$quote_id in the function. you can remove it. and call function with single parameter that is array $quote
Why don't you try this:
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
echo '<h1>' . $random["quote"] . '.</h1><br>';
echo '<p>' . $random["attribution"] . '</p>';
Want to create a function:
echo get_random_quote($quotes);
function get_random_quote($quotes) {
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
return '<h1>' . $random["quote"] . '.</h1><br>'.'<p>' . $random["attribution"] . '</p>';
}
First, you dont need the $quote_id in get_random_quote(), should be like this:
function get_random_quote($quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
}
And I cant see anything random that the function is doing. You are just iterating through the array:
foreach($quotes as $quote_id => $quote) {
echo get_random_quote( $quote);
}
According to http://php.net/manual/en/function.array-rand.php:
array_rand() Picks one or more random entries out of an array, and
returns the key (or keys) of the random entries.
So I guess $quote[$random_quote] should return your element, you can use it like:
$random_quote = array_rand($quotes);
echo get_random_quote($quote[$random_quote]);

PHP foreach loop read files, create array and print file name

Could someone help me with this?
I have a folder with some files (without extention)
/module/mail/templates
With these files:
test
test2
I want to first loop and read the file names (test and test2) and print them to my html form as dropdown items. This works (the rest of the form html tags are above and under the code below, and omitted here).
But I also want to read each files content and assign the content to a var $content and place it in an array I can use later.
This is how I try to achieve this, without luck:
foreach (glob("module/mail/templates/*") as $templateName)
{
$i++;
$content = file_get_contents($templateName, r); // This is not working
echo "<p>" . $content . "</p>"; // this is not working
$tpl = str_replace('module/mail/templates/', '', $templatName);
$tplarray = array($tpl => $content); // not working
echo "<option id=\"".$i."\">". $tpl . "</option>";
print_r($tplarray);//not working
}
This code worked for me:
<?php
$tplarray = array();
$i = 0;
echo '<select>';
foreach(glob('module/mail/templates/*') as $templateName) {
$content = file_get_contents($templateName);
if ($content !== false) {
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"$i\">$tpl</option>" . PHP_EOL;
} else {
trigger_error("Cannot read $templateName");
}
$i++;
}
echo '</select>';
print_r($tplarray);
?>
Initialize the array outside of the loop. Then assign it values inside the loop. Don't try to print the array until you are outside of the loop.
The r in the call to file_get_contents is wrong. Take it out. The second argument to file_get_contents is optional and should be a boolean if it is used.
Check that file_get_contents() doesn't return FALSE which is what it returns if there is an error trying to read the file.
You have a typo where you are referring to $templatName rather than $templateName.
$tplarray = array();
foreach (glob("module/mail/templates/*") as $templateName) {
$i++;
$content = file_get_contents($templateName);
if ($content !== FALSE) {
echo "<p>" . $content . "</p>";
} else {
trigger_error("file_get_contents() failed for file $templateName");
}
$tpl = str_replace('module/mail/templates/', '', $templateName);
$tplarray[$tpl] = $content;
echo "<option id=\"".$i."\">". $tpl . "</option>";
}
print_r($tplarray);

JSON Fatal Error foreach

I´ve got the following:
include('php/get_recipe_byID.php');
$jsonstring1 = $recipe_byidarr;
$recip = json_decode($recipe_byidarr, true);
print_r($recip);
foreach ($recip['Data']['Recipes'] as $key => $newrecipe) {
// echo '<li>
// <a href="/recipe_search.php?id=' . $recipe['ID'] . '">';
echo 'seas';
echo $newrecipe['TITLE'];
echo '<br><br>';
}
When I call it in the browser, it tells me that
Fatal error: Cannot use string offset as an array in /var/www/recipe_search.php on line 43
This is the line of the foreach loop.
$recip is the following:
{"Data":{"Recipes":{"Recipe_9":{"ID":"9","TITLE":"Schnitzel","TEXT":"Alex\u00b4s Hausmannskost","COUNT_PERSONS":"4","DURATION":"40","USER_ID":"1","DATE":"2011-09-16 00:00:00"}}},"Message":null,"Code":200}
Do anybody know where my mistake is?
Just try it:
$taskSeries = $array['Data']['Recipes']['Recipe_'.$_GET['id']];
if(array_key_exists('TITLE', $taskSeries)) {
$taskSeries = array($taskSeries);
}
foreach($taskSeries as $task) {
$title = $task['TITLE'];
// do something with $title and other
}

Is there something wrong with this foreach code?

foreach ($data['tests'] as $testname => $tests) {
echo "<h1>Extraction $testname Tests</h1>\n";
$function = $testfunctions[$testname];
echo "<ul>";
foreach ($tests as $test) {
echo "<li>" . $test['description'] . ' ... ';
$extracted = $extractor->$function($test['text']);
if ($test['expected'] == $extracted) {
echo " <span style='color: green'>passed.</span></li>";
} else {
echo " <span style='color: red'>failed.</span>";
echo "<pre>Original: " . htmlspecialchars($test['text']) . "\nExpected: " . print_r($test['expected'], true) . "\nActual : " . print_r($extracted, true) . "</pre>";
}
echo "</li>";
}
echo "</ul>";}
I keep getting the error:
Warning: Invalid argument supplied for
foreach() in
C:\xampp\htdocs\test\runtests.php on
line 49
p.s. the beginning of the code is line 49, so the probelm starts with the foreach statment.
Whenever i see that, it tends to mean that the thing i'm trying to iterate through isn't an array.
Check $data['tests'] (and each inner $tests) to make sure it's not null/unset/empty, and that it's something iterable like an array. Also keep in mind that older versions of PHP (before 5.0?) don't do iterable objects very well.
One of the elements in $data["tests"] is probably not an array.
Add this before the foreach:
if (is_array($tests))
foreach ($tests as $test) {...

Categories