I'm trying to get this function to work but for some reason it errors out on the foreach line saying there is an invalid argument.
$scores= TESTAPI::GUL($user->ID);
if (empty($scores)) {
echo "<p>No Scores</p>";
} else {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
}
The error I get is: PHP Warning: Invalid argument supplied for foreach()
For example, empty('') would also be true.
I would recommend to check is_array($scores) && count($scores) instead of empty(), to make sure the api returned useable output (an array) and that this contains elements (count() > 0 which is true).
$scores = TESTAPI::GUL($user->ID);
if (is_array($scores) && count($scores)) {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
} else {
echo "<p>No Scores</p>";
}
Try this -
foreach ((array) $scores as $score) { ...
Looks like $scores is neither an array nor an object...
Related
$cursor = $collection->find(/*...*/);
if (empty($cursor)) {
echo "List is empty!";
} else {
foreach ($cursor as $products) {
// do something
}
}
Unfortunately, empty doesn't work on MongoDB results.
we can use the isDead() method of the cursor
if (!$products->isDead()) {
// there are some results
}
See the relevant documentation on the PHP driver docs
I don't use MongoDB so I have updated based on the comment. Use $collection->count().
Check if it evaluates to a falsey value:
if(!$collection->count()) {
Or check for 0:
if($collection->count() == 0) {
Or you could check empty:
if(empty($collection->count())) {
$cursor is an object so it will always evaluate to true
and there is no $cursor->count() in PHP driver for mongodb
Note that PHP driver for Mongodb is different from other drivers.
Try this:
if ($collection->count(...)) {
// note you must pass the query to the count function
$cursor = $collection->find(...);
foreach ($cursor as $products) {
}
} else {
echo "List is empty!";
}
OR:
$cursor = $collection->find(...);
if (!count($cursor->toarray())) { // convert to array and count it
echo "List is empty!";
} else {
foreach ($cursor as $products) {
}
}
$numofOfficer = sizeof($_POST['officer']); // = 2
for ($cntr = 0; 0 < $numOfficer; $cntr++)
{
foreach ($_POST['officer'][$cntr] as $index => $value)
{
// DO SOMETHING HERE...
}
}
Please help. I don't how to fix this warning.
The argument of foreach is an array having 2 length and 2 dimension. BUT, the other codes same with this went well, same length and length dimension of array argument. I just cant figure what is difference of the code above to the other.
There is no need to use for and foreach doing the same. You can omit the for and reduce you code to:
if (is_array($_POST['officer']))
{
foreach ($_POST['officer'] as $officer)
{
foreach ($officer as $index => $value)
{
// DO SOMETHING HERE...
}
}
}
To check to see if each foreach() statement applies to an array, the first argument in each statement is (array). Despite this argument, the below code isn't returning any data.
The script is designed to pull applicable data from the FAA's XML Airport Status JSP file (http://www.fly.faa.gov/flyfaa/xmlAirportStatus.jsp) given the data supplied via the $airports variable.
Upon removal of the (array) argument in each foreach() statement, the script returns applicable data but also returns the following warning:
Warning: Invalid argument supplied for foreach()
Code:
$xml = simplexml_load_file("http://www.fly.faa.gov/flyfaa/xmlAirportStatus.jsp");
$airports = array('ATL','AUS','BOS','DEN','LAS','LGA','LGB','JFK','OAK','PDX','PHX','RNO','SAN','SAT','SEA','SFO','SJC','SLC','SMF');
$effected = array();
$count = 0;
foreach((array) $xml->Delay_type as $Delay) {
foreach((array) $Delay->Ground_Stop_List->Program as $Program) {
if(in_array($Program->ARPT, $airports)) {
$effected[] = $Program->ARPT;
if($count == 0) {
echo '<div class="alert">';
}
echo 'Departure traffic destined to <b>'.$Program->ARPT.'</b> is being held at its origin due to <b>'.$Program->Reason.'</b> until <b>'.$Program->End_Time.'</b><br />';
$count++;
}
}
foreach((array) $Delay->Ground_Delay_List->Ground_Delay as $Ground_Delay) {
if(in_array($Ground_Delay->ARPT, $airports)) {
$effected[] = $Ground_Delay->ARPT;
if($count == 0) {
echo '<div class="alert">';
}
/* effected[] = $Ground_Delay->ARPT; */
echo 'Departure traffic destined to <b>'.$Ground_Delay->ARPT.'</b> is facing an average delay of <b>'.$Ground_Delay->Avg.'</b> due to <b>'.$Ground_Delay->Reason.'</b><br />';
$count++;
}
}
}
I am trying to generate an MS Excel spread sheet using PHPExcel 1.7.6 . I am having trouble determining the structure of the array expected.
The code that builds up the columns and rows is as follows:
function _headers() {
$i=0;
foreach ($this->data[0] as $field => $value) {
if (!in_array($field,$this->blacklist)) {
$columnName = Inflector::humanize($field);
$this->sheet->setCellValueByColumnAndRow($i++, 4, $columnName);
}
}
$this->sheet->getStyle('A4')->getFont()->setBold(true);
$this->sheet->getStyle('A4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$this->sheet->getStyle('A4')->getFill()->getStartColor()->setRGB('969696');
$this->sheet->duplicateStyle( $this->sheet->getStyle('A4'), 'B4:'.$this->sheet->getHighestColumn().'4');
for ($j=1; $j<$i; $j++) {
$this->sheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($j))->setAutoSize(true);
}
}
function _rows() {
$i=5;
foreach ($this->data as $row) {
$j=0;
foreach ($row as $field => $value) {
if(!in_array($field,$this->blacklist)) {
$this->sheet->setCellValueByColumnAndRow($j++,$i, $value);
}
}
$i++;
}
}
I'm currently getting an 'Invalid argument supplied for foreach()' error.
I would appreciate it if somebody can outline the correct array structure required.
As IsisCode said, it sounds like you're looking in the wrong direction by associating the problem with PHPExcel. That error is generally just saying that the first argument supplied to foreach() isn't an array.
I don't see anything indicating that the problem is explicitly with the initial foreach in the _headers() method though. If there's a non array element in $this->data then your _rows() method could produce the error as well.
Given:
$this->data = Array(
Array('foo' => 'bar'),
'baz'
)
That would cause the second foreach in _rows() to fail, as an example. Your error message should be able to point you to which foreach() is failing, but ultimately it sounds like you've got a non-array element in $this->data where you don't expect it. If that can't be helped, then consider verifying you're dealing with an array before calling foreach:
function _rows() {
$i=5;
foreach ($this->data as $row) {
$j=0;
if(!is_array($row)) { continue; } // Ignore non-array elements
foreach ($row as $field => $value) {
if(!in_array($field,$this->blacklist)) {
$this->sheet->setCellValueByColumnAndRow($j++,$i, $value);
}
}
$i++;
}
Verifying the type of a variable before handing it to a type-specific function is never a bad idea and can save a lot of headache in general.
I have some code I created which is supposed to see if something exists in an array of strings. If it does not exist, I want to delete that element of the array. I thought we do this with unset, but it doesnt seem to be working. Mind helping?
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($game);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);
output:
size of $games before end-check: 2
end of game found
end of game not found. incomplete game
size of $games after end-check: 2
Because you unset the variable $game, not the element in the array. Try this:
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $index => $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($games[$index]);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);
You have to unset the index of game.
foreach ($games as $key => $value) {
// all your logic here, performed on $value
unset($games[$key]);
}
This merely unsets your local reference to the element. You need to be referring directly to the array.
foreach($games as $key => $game)
unset($games[$key]);
That won't work: foreach creates a new variable, copying the old one. Unsetting it will do nothing to the original value. Likewise, making it a reference won't work either, since only the reference would be deleted.
The nicest way to do this would be with array_filter:
$games = array_filter($games, function($game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
return true;
}
else {
echo "<br>end of game not found. incomplete game";
return false;
}
});
This uses the anonymous function syntax introduced in PHP 5.3. If the function returns true, the element is kept; if it returns false, the element is removed.
You can also call by reference:
foreach($games as &$game) {
unset($game);
}
In this way you can also change $game (eg. $game .= " blah";) and the original array will be modified.
You can use array_splice in conjunction with an incrementally-increasing index variable to remove the current item from the array:
$index = 0;
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
array_splice($games, $index, 1);
}
$index++;
}