I've been going mad trying to figure out why an array would not be an array in php.
For a reason I can't understand I have a bug in a smarty class. The code is this :
$compiled_tags = array();
for ($i = 0, $for_max = count($template_tags); $i < $for_max; $i++) {
$this->_current_line_no += substr_count($text_blocks[$i], "\n");
// I tried array push instead to see
// bug is here
array_push($compiled_tags,$this->_compile_tag($template_tags[$i]));
//$compiled_tags[] = $this->_compile_tag($template_tags[$i]);
$this->_current_line_no += substr_count($template_tags[$i], "\n");
}
the error message is
Warning: array_push() expects
parameter 1 to be array, integer given
in ....
OR before with []
Warning: Cannot use a scalar value as
an array in ....
I trying a var_debug on $compiled_tags and as soon I enter the for loop is not an array anymore but an integer. I tried renaming the variable, but same problem.
I'm sure is something simple that I missed but I can't figure it out. Any help is (as always) welcomed !
The variable $compiled_tags is getting overwritten by something, probably the method call.
Try adding print_r($compiled_tags); between each line and then see where it changes from an empty array to a scalar. I would bet it happens after the method call $this->_compile_tag()
As far as I'm aware, $compiled_tags[] will ALWAYS work. There may be a problem somewhere else in your code. Maybe _compile_tag() uses $compiled_tags as a global?
What's the scope of $compiled_tags?
It looks like the method _compile_tag(...) may be setting it to an integer.
Related
I finally got round to updating my PHP install to 7.4 from 7.2 (Planning on going right to current but doing in steps) and a curious error appeared when I was running an existing script:
Message: Trying to access array offset on value of type null
The line that this appears on is simply to populate an array from a simple mysql result set.
for($i = 0; $resultArray[$i] = mysqli_fetch_row($result)[0]; $i++) ;
The script still continues fine but I just don't like any errors. I'm scratching my head why this has errored and searched for a few hours to no avail. Why is this erroring and is there a way to do the same thing with no error?
mysqli_fetch_row will return null at some point (as it always does when it runs out of rows to retrieve, as per the documentation). But you're not checking that before trying to read its 0th index, hence the error.
Many people retrieve rows using this kind of style:
while ($row = mysqli_fetch_row($result)) {
$resultArray[] = $row[0];
}
which will avoid this sort of problem. That's the way you'll often see it done in examples and documentation, too.
As per the documentation mysqli_fetch_row will return null once it reaches the end of the result set.
You can use a foreach loop. I wouldn't recommend it, but it's a possible solution.
foreach ($result->fetch_all() as [0 => $resultArray[]]); // no body needed
You don't really need to use this strange contraption. You can do it even simpler using array_column().
$resultArray = array_column($result->fetch_all(), 0);
Im completely new to PHP, please dont judge me by code it is not of my doing Im just fixing someone elses poor code. I got a task in job to fix issue with count() function.
Theres variable called $var which has a result function count() with variable in it.
the problem is that I get error on this line
$has = count($var); // Message: count(): Parameter must be an array or an object that implements Countable
Heres the snippet of the code:
if($l)
foreach($list[$key] as $k=>$v){
$var = #$c->content->config['has'][$v['type']];
$has = count($var);
echo '<li class="',($k==$l-1?'last ':''),($has?'folder ':'file ' ),(isset($list[$v['url']])?'open ':''),'type_',($v['type']),'"><span onClick="tree_tog(this)"></span>',character_limiter($v['name'],40),'';
if($v['type']!='root'&&isset($list[$v['url']]))
pr($list,$v['url'],$c);
echo '</li>';
}
How can I fix this error? Anyone? please!!
See the documentation for the count() function.
In your code, you have,
$has = count($var);
This means you are trying to count the elements of $var or more specifically, the object or literal that the $var variable refers to. Now, the count function can count elements of an array or any other object that is said to be countable. Not everything is countable. For instance, if you have an integer variable $price = 200; then the variable does not contain any elements in it, rather it has a number. So, the count function cannot count (the elements of) $price variable. Although, you could measure the length of the variable but that would be different than counting.
Simply put, you can count elements of an array or an object that has its properties structured in a way so that they can be countable. Otherwise, count() will fail and show that warning.
Try printing out the variable and see if you can figure out what's in it. There are several ways to print/debug in PHP objects,
print_r($var);
Or,
var_dump($var);
Happy coding.
If you are a PHP developer you most probably have seen the following notice:
Notice: Only variables should be passed by reference in /somefile.php
on line xxx
(Problem extensivley treated in Only variables should be passed by reference)
Example throwing notice:
$string = "hi-dude";
echo end(explode('-', $string));
Working example:
$string = "hi-dude";
$strings = explode('-', $string);
echo end($strings);
Explanation:
Only real variables may be passed by reference, not functions which are returning the correct variable.
However I can not think of a good reason why this notice is happening. It feels unecessary and requires me to write a lot of extra lines of code sometimes. What is the reason for PHP having this strange restriction? Why does this problem even exist?
end() or array_pop() will return the E_NOTICE with message
Only variables should be passed by reference
The reason is that end() requires a reference, because it makes the current element pointer point to the last element.
You can do it with one line,
$string = "this-is-a-sample-text";
echo substr(strrchr($string, '-'), 1);
DEMO: https://3v4l.org/jO29n
Finally I found a great explanation which helped me to understand this: What's the difference between passing by reference vs. passing by value?
As Daniel Pryden states:
In simplest terms:
call by value means that you pass values as function arguments
call by reference means that you pass variables as function arguments
In metaphoric terms:
Call by value is where I write down something on a piece of paper and hand it to you. Maybe it's a URL, maybe it's a complete copy of
War and Peace. No matter what it is, it's on a piece of paper which
I've given to you, and so now it is effectively your piece of paper.
You are now free to scribble on that piece of paper, or use that piece
of paper to find something somewhere else and fiddle with it,
whatever.
Call by reference is when I give you my notebook which has something written down in it. You may scribble in my notebook (maybe I
want you to, maybe I don't), and afterwards I keep my notebook, with
whatever scribbles you've put there. Also, if what either you or I
wrote there is information about how to find something somewhere else,
either you or I can go there and fiddle with that information.
In this case the notice "Only variables should be passed by reference" is still unjustified as we are only interested in retrieving the last value of the array. However the function end() is defined like
mixed end ( array &$array )
The & sign which states passing by reference is there for a certain reason: end() is not just returning the last element of an array, it also changes its internal pointer to the end. Therefore the array is modified.
If we only would return the last element of an array without touching the array there would be no need to pass the array by reference and we would not get this notice. But end() is somehow the wrong function for that.
What if there is no justification for me getting this notice?
Note that also the function to be called might be defined wrong. In my case I hade a function defined like this:
/**
* Flatten an array by one level if only needing a certain key value from a sub array.
*
* Example: [["foo"=>"bar","foo"=>"cheese"]]
* Result: ["bar","cheese"]
*
* #param $array: The input array.
* #param $key: The key to flatupshift. Default is 0.
* #return $array: The result
*/
private function array_flatupshift(&$array, $key = 0) {
$a = [];
foreach ($array as $item) {
if (is_object($item)) {
array_push($a, $item->$key);
} else if (is_array($item)) {
array_push($a, $item[$key]);
}
}
return $a;
}
This is simply a wrong function definition. So if you also get notices like this: Check if the function you call is defined correctly. Passing by reference does not make sense here as the array being passed is not touched in any way. Therefore the function definition should be without the "reference &/":
private function array_flatupshift($array, $key = 0) {
There are some cases where you MIGHT use the error control operator if you know what you are doing. Therefore:
$string = "hi-dude";
echo #end(explode('-', $string));
... would be o.k. I guess is the result of explode is not needed anymore. However notice the drawbacks of suppressing all possible errors. Please correct me if I go wrong here.
I feel stupid for asking this cause it seems so basic but it's really bugging me.
I have a method that returns an array with a single element. I just want it to return the element not wrapped in an array. I tried this.
return $f->getValue()[0];
and it gives an error but if I save it to a variable, it works fine.
$v = $f->getValue();
return $v[0];
I can't figure it out....
It's available only since PHP 5.4: http://codepad.viper-7.com/VHOW0o
What you are trying to do, is called array dereferencing, and is only possible in PHP as of version 5.4 (if you scroll up a few lines in the documentation article I linked to, you'll see it mentioned).
Use reset().
<?php return reset( $f->getValue() ); ?>
Edit: reset() is probably superior to current() as it also makes sure that the internal pointer is reset, despite it not making much difference if the array only contains one element.
As far as I know since you are returning an array you only can get an array. You can instead save the array to a variable in the class (accessible by $f->myArray) and then return just the string portion. Or the other option is to do what your second example is and return the array and retrieve the string from it.
have you tried this
<?php
return array_shift(array_values($array));
?>
Get the first element of an array
I have this array:
$array = array();
$array['123'] = 'abc';
$array['456'] = 'def';
Now I would like to get data from that array based on a variable. This is what I tried:
$variable = '123';
$result = $array[$variable];
echo $result;
It appears to be wrong, but i don't know why. It results in a warning:
Illegal offset type […]
I ran that exact code into my compiler and it worked; possibly it is a white-space error (random characters you cant see but still cause bugs). I would try to physically retype that section of code and delete the old one.
I would suggest trying this to make sure the variable is cast as a string:
$result = $array[(string)$variable];
That's most likely your problem. I think maybe $post['id'] is either mistakenly a multi-dimensional array or somehow becoming an object of a type not accepted as an array key.