I am trying to remove an Article object from an array inside a foreach loop but I am getting the error
Fatal error: Cannot use object of type Article as array
foreach ($articles as $i => $article) {
foreach ($categorys as $category) {
if (checkCategory($category,$article)) {
unset($article[$i]);
}
}
if ($userName != Null) {
if ($article->getUserName() != $userName) {
unset($article[$i]);
}
}
if ($keyWords != Null) {
if (!containsKeyWords($keyWords, $article)) {
unset($article[$i]);
}
}
}
You have to unset from $articles array(main or parent array).so do like below:-
unset($articles[$i])
The error gives me some clue that your $article may not be an array but an stdClass Object, you can usevar_dump to check its type.
you can unset an object using unset($article->{$i}) or unset($article->somekey).
Hope it helps.
$article is of an Object type and you're trying to access it via array type.
Try var_dump() to check it's type & then accordingly use unset.
For array type : unset($article[$i])
For object type : unset($article->{$i}) where $i is key
How can I retrieve a data from my database in the controller, and assign it to a variable, that I will send to the view?
$data['schedule'] = $this->SectionsModel->getschedule($section);
I want the
$schedule['teacher']
(as equivalent to a view) data from the statement above to be passed to a variable, but how?
I tried this one but it shows an error
$data['schedule'] = $this->SectionsModel->getschedule($section);
foreach ($data['schedule'] as $key => $value){
echo $value['teacher'];
}
may be you can use result_array() in return value of your model.
Check your getschedule() method in your SectionModel if it's using the function result() instead of result_array().
The difference between the two methods is that result() will return object while result_array() will return array.
In you case,
$data['schedule'] = $this->SectionsModel->getschedule($section);
foreach ($data['schedule'] as $key => $value){
echo $value['teacher'];
}
Maybe $data['schedule'] is an object.You must use,
$data['schedule'] = $this->SectionsModel->getschedule($section);
foreach ($data['schedule'] as $key => $value){
echo $value->teacher;
}
If you will use result_array() method in your getschedule() in SectionModel to return result, do like this,
$data['schedule'] = $this->SectionsModel->getschedule($section);
foreach ($data['schedule'] as $key => $value){
echo $value['teacher'];
}
Hope this will help.
It often happens to me to handle data that can be either an array or a null variable and to feed some foreach with these data.
$values = get_values();
foreach ($values as $value){
...
}
When you feed a foreach with data that are not an array, you get a warning:
Warning: Invalid argument supplied for foreach() in [...]
Assuming it's not possible to refactor the get_values() function to always return an array (backward compatibility, not available source code, whatever other reason), I'm wondering which is the cleanest and most efficient way to avoid these warnings:
Casting $values to array
Initializing $values to array
Wrapping the foreach with an if
Other (please suggest)
Personally I find this to be the most clean - not sure if it's the most efficient, mind!
if (is_array($values) || is_object($values))
{
foreach ($values as $value)
{
...
}
}
The reason for my preference is it doesn't allocate an empty array when you've got nothing to begin with anyway.
How about this one? lot cleaner and all in single line.
foreach ((array) $items as $item) {
// ...
}
I usually use a construct similar to this:
/**
* Determine if a variable is iterable. i.e. can be used to loop over.
*
* #return bool
*/
function is_iterable($var)
{
return $var !== null
&& (is_array($var)
|| $var instanceof Traversable
|| $var instanceof Iterator
|| $var instanceof IteratorAggregate
);
}
$values = get_values();
if (is_iterable($values))
{
foreach ($values as $value)
{
// do stuff...
}
}
Note that this particular version is not tested, its typed directly into SO from memory.
Edit: added Traversable check
Please do not depend on casting as a solution,
even though others are suggesting this as a valid option to prevent an error, it might cause another one.
Be aware: If you expect a specific form of array to be returned, this might fail you. More checks are required for that.
E.g. casting a boolean to an array (array)bool, will NOT result in an empty array, but an array with one element containing the boolean value as an int: [0=>0] or [0=>1].
I wrote a quick test to present this problem.
(Here is a backup Test in case the first test url fails.)
Included are tests for: null, false, true, a class, an array and undefined.
Always test your input before using it in foreach. Suggestions:
Quick type checking: $array = is_array($var) or is_object($var) ? $var : [] ;
Type hinting arrays in methods before using a foreach and specifying return types
Wrapping foreach within if
Using try{}catch(){} blocks
Designing proper code / testing before production releases
To test an array against proper form you could use array_key_exists on a specific key, or test the depth of an array (when it is one !).
Always extract your helper methods into the global namespace in a way to reduce duplicate code
Try this:
//Force array
$dataArr = is_array($dataArr) ? $dataArr : array($dataArr);
foreach ($dataArr as $val) {
echo $val;
}
;)
$values = get_values();
foreach ((array) $values as $value){
...
}
Problem is always null and Casting is in fact the cleaning solution.
foreach ($arr ?: [] as $elem) {
// Do something
}
This doesen't check if it is an array, but skips the loop if the variable is null or an empty array.
Update from PHP 7.0 you should use the null coalescing operator:
foreach ($arr ?? [] as $elem) {
// Do something
}
This would solve the warning mentioned in the comment (here a handy table that compares ?: and ?? outputs).
First of all, every variable must be initialized. Always.
Casting is not an option.
if get_values(); can return different type variable, this value must be checked, of course.
If you're using php7 and you want to handle only undefined errors this is the cleanest IMHO
$array = [1,2,3,4];
foreach ( $array ?? [] as $item ) {
echo $item;
}
As of PHP >= 7.1.0 use is_iterable
https://www.php.net/manual/en/function.is-iterable.php
if (is_iterable($value)) {
foreach ($value as $v) {
...
}
}
More concise extension of #Kris's code
function secure_iterable($var)
{
return is_iterable($var) ? $var : array();
}
foreach (secure_iterable($values) as $value)
{
//do stuff...
}
especially for using inside template code
<?php foreach (secure_iterable($values) as $value): ?>
...
<?php endforeach; ?>
Warning invalid argument supplied for foreach() display tweets.
go to /wp-content/plugins/display-tweets-php.
Then insert this code on line number 591, It will run perfectly.
if (is_array($tweets)) {
foreach ($tweets as $tweet)
{
...
}
}
This warning is happening because the array that you want use is empty, you can use of below condition:
if ($your_array != false){
foreach ($your_array as $value){
echo $value['your_value_name'];
}
}
There seems also to be a relation to the environment:
I had that "invalid argument supplied foreach()" error only in the dev environment, but not in prod (I am working on the server, not localhost).
Despite the error a var_dump indicated that the array was well there (in both cases app and dev).
The if (is_array($array)) around the foreach ($array as $subarray) solved the problem.
Sorry, that I cannot explain the cause, but as it took me a while to figure a solution I thought of better sharing this as an observation.
Exceptional case for this notice occurs if you set array to null inside foreach loop
if (is_array($values))
{
foreach ($values as $value)
{
$values = null;//WARNING!!!
}
}
I'll use a combination of empty, isset and is_array as
$array = ['dog', 'cat', 'lion'];
if (!empty($array) && isset($array) && is_array($array) {
//loop
foreach ($array as $values) {
echo $values;
}
}
Use is_array function, when you will pass array to foreach loop.
if (is_array($your_variable)) {
foreach ($your_variable as $item) {
//your code
}
}
How about this solution:
$type = gettype($your_iteratable);
$types = array(
'array',
'object'
);
if (in_array($type, $types)) {
// foreach code comes here
}
What about defining an empty array as fallback if get_value() is empty?
I can't think of a shortest way.
$values = get_values() ?: [];
foreach ($values as $value){
...
}
<?php
if (isset($_POST['checkbox'])) {
$checkbox = $_POST['checkbox'];
foreach ($checkbox as $key) {
echo $key . '<br>';
}
}
?>
<input type="checkbox" name="checkbox[]" value="red">red <br>
<input type="checkbox" name="checkbox[]" value="green">green <br>
I have this function:
function extractAvailable($assoc1, $assoc2){
if($assoc1) extract($assoc1);
else extract($assoc2);
}
What I expect is to call this function later in the global scope, and have my variables available, like so:
$arr1 = [];
$arr2 = ['one'=>1, 'two'=>'SecondItem'];
extractAvailable($arr1, $arr2);
With the call on extractAvailable(), I need to have the varialbes $one and $two available in the current scope. Obviously, I've got something wrongly figured concerning variable scope use here, 'cause it isn't working. When I try to use the variable, what I get instead is Notice: Undefined variable: one.
How do I get this to work?
You could add the new data to the $GLOBALS array which would have the effect of making them available in other scopes.
function extractAvailable($assoc1, $assoc2){
if($assoc1) {
foreach ($assoc1 as $key => $value) {
$GLOBALS[$key] = $value;
}
} else {
foreach ($assoc2 as $key => $value) {
$GLOBALS[$key] = $value;
}
}
}
But I have to wonder why you need to extract anything from a perfectly good array and place the exact same data into scalar variables.
All this does is double your memory requirement for no benefit whatsoever
If you want them to be available in the global scope, you can use variable variables instead of extract, and specify them as global.
function extractAvailable($assoc1, $assoc2){
if($assoc1) {
foreach ($assoc1 as $key => $value) {
global $$key;
$$key = $value;
}
} else {
foreach ($assoc2 as $key => $value) {
global $$key;
$$key = $value;
}
}
}
I would like to loop through the contents of a query object update certain values and return the object.
function clearAllIds($queryObject)
{
foreach($queryObject->result() as $row)
{
$row->id = 0;
}
return $queryObject
}
In this example I would like to zero out all of the ID values. How can I accomplish this within the foreach loop?
Please excuse the formatting.
This entirely depends on what the class of your query object is, and whether or not you'll be able to Pass by reference.
Assuming your $queryObject->result() can be delivered in a write-context, you could preface the $row with an ampersand to pass it by reference, like so:
foreach($queryObject->result() as &$row)
{
$row->id = 0;
}
function clearAllIds($queryObject)
{
foreach($queryObject->result() as &$row)
{
$row->id = 0;
}
return $queryObject
}
Use the & operator to get $row as a reference.
Edit: This will work if $queryObject is an array. You should probably do
$data = $queryObject->result();
foreach($data as &$row) { ... }
return $data;
function trim_spaces($object)
{
foreach (get_object_vars($object) as $property=> $value)
{
$object->$property=trim($value);
}
}
//no need to return object as they are passed by reference by default