I got used to this notation for creating empty arrays and add named elements to them when needed;
$array = [];
// in case there is an error
$array["error"][] = "new error message as element 0 of $array['error']";
Now I learned that the [] notation for arrays does not work in older versions of PHP, like PHP 5.2.
Instead I have to do;
$array = array(
"error" => array()
);
array_push($array["error"], "new error message as element 0 of $array['error']");
This way is a little bit inconvenient in my case because the great thing about the first code snippet is that the "error" entry in $array is only created when there is an actual error, whereas in the latter case the entry (although empty) exists either way.
Is there a way to get similar 'functionality' (i.e. specifying/adding named elements when needed, not at initialisation) in a way that is also easily readable in PHP 5.2?
EDIT:
The first code snippet in the original post was reading $array = array[];. The author corrected it after I posted this answer.
The first code snipped is incorrect. There is no such thing as array[]. The correct syntax is array().
$array = array();
// in case there is an error
$array["error"][] = "new error message as element 0 of $array['error']";
You don't have to worry about PHP versions. This syntax always worked on PHP since its dawn and it will probably work forever. Keep using it.
The first way of creating array in PHP is incorrect. This syntax works in PHP5.2 below too, so you dont need to worry about it. You don't need to use array_push and simply do following.
The correct syntax is:
$array = array(); // notice it doesn't to array[]
// add error when there is one
$array["error"][] = "new error message as element 0 of $array['error']";
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);
$pairs = []; // Clear the pairs array
$pairs['post_name'] = $post->post_name; // Hold the post_name for the error function's use
$pairs['post_id'] = $post->ID; // Hold the post ID for the error function's use
$pairs['tag'] = $tag; // Add the tag to the pairs array for the error function's use
The above is code to define an array then set a few values. This is throwing an error that I suspect is complaining because I didn't pre-define the keys, but I also don't want to. One of the biggest advantages of PHP is that it's not necessary to pre-define and allocate every little thing when it's obvious from context.
Is there a simple way of solving this problem without having to predefine the entire array and all it's keys? I tried changing the definition to $pairs = {} on the hopes it would be happier, but no dice. I suspect this is a problem with updating to PHP 8 and am tempted to turn off warnings, but would rather do it "right" (unless that means predefining everything).
EDIT: TO be clear, the error listed in the title applies to ALL of the above assignments and any other similar assignments in my code. I'm getting a hundred or more instances of this error because I've always created array keys on assignment like this before and I'd like to keep doing so.
I recently came across the following snippet of code:
#$this->responseData[$this->currentTag] .=$data;
Which seems to add $data to the array at the specified index. Without error suppression, this causes an error (Undefined index DataKey). The key used was a string "DataKey". and the data was a string.
I cannot find any documentation on using .= with arrays. Why does it give an error?
I do not want to simply suppress the error and move on. And yes, I could just use = instead of .=. The application may be using responseData for string handling as well as array handling (it is very bad code!!).
Any help would be awesome.
It is concatenating assignment operaotor.I dont know actually what do you want to do it with the arrays..Please edit your question on what you need ..The concatening assignment operator appends the argument on the right side to the argument on the left side.
Couldn't you just build an actual array?
$tags = [Your query to build the array of all tag data]
$tagnames = array(); // The array for tag names
foreach ($tags as $tag) {
$tagnames[] = $tag->tagname;
}
print_r($tagnames);
I'm getting some weird behaviour in PHP that I just can't understand.
$count=0;
$temp=array(); //this is definitely a new variable, not that it should matter
foreach($array as $arr) {
if ($arr->bbcode != $previous_bb) {
$previous_bb=$arr->bbcode;
//stuff
$temp=array_merge($temp,$arr);
}
//stuff
}
I've tried to simplify the code a little and just keep what's essential. $array is a 2-D array (so each $arr has some attributes like the bbcode that you see). It complains that argument 1, i.e. $temp, is not an array. Typecasting it to array gives bogus results. Of course, this is within other code, which I can give more details of if needed, but any ideas? I've used the exact same sort of code and syntax in other places and it doesn't complain...
EDIT: Feel free to downvote liberally, had a memory lapse about what I had been working with and how I'd been doing things. Never had to ask a programming question before (in several years), thanks a ton guys, you are immensely fast!
Let's look at your two arguments.
$temp is initialised as array(), and repeatedly assigned to the return value of array_merge which (unless things go wrong) is always an array.
$arr. Well, it's in the name, right? That's about as reliable as $two = 3;. You are accessing $arr->bbcode so it is clearly an object and not an array.
Did you mean $temp[] = $arr;?
You are trying to merge an object ($arr) with an array ($temp). PHP should complain that $arr is not an array. See the example code below:
php > $obj = new StdClass();
php > $obj->property = "value";
php > $arr = [];
php > array_merge($arr, $obj);
Warning: array_merge(): Argument #2 is not an array in php shell code on line 1
Call Stack:
33.2510 230352 1. {main}() php shell code:0
33.2510 230960 2. array_merge() php shell code:1
Typecasting in php is always a bit tricky, if you do so check the type juggling documentation to see what happens when.
Before trying to optimize your code, what do you want to achieve? A new list which is cleaned of duplicate bb codes?
I had some code added that deals with canonical links but it doesn't seem to be working. One line of code that is repeated in several files shows a red mark next to it in Dreamweaver so i suspect this is wrong.
$pid = explode('=',explode('&',$_SERVER['QUERY_STRING'])[0]);
Can anyone see an obvious reason this would be flagged up by DW. I don't see any unclosed brackets or ' in it so i'm a bit lost.
Update:
It appears there is a fundamental error in the original code as the var $pid[1] is never given the correct data.
I tried using the split code answer below and if i print_r this
$qs = explode('&',$_SERVER['QUERY_STRING']);
the result is Array ( [0] => main_page=index [1] => cPath=70_229_242_240 )
Then print_r the second part
$pid = explode('=',$qs[0]);
gives a result of index
This is incorrect.
A simplified version of the code using the results is
if($pid[1] == '70_229_242_240'){
echo " true";
}
So you can see that what I actually need to have stored in $pid is taken from cPath=70_229_242_240
I've tried to change the explode to give me this data but i can't get the correct result. TBH, they always confuse the hell out of me.
RESOLVED.
Used $pid = explode('=',$qs[1]);
You can possibly change this code into:
$qs = explode('&',$_SERVER['QUERY_STRING']);
$pid = explode('=',$qs[0]);
to get rid of this red mark.
But in fact Dreamweaver is not a PHP editor, you should simple choose something else to write your PHP code.
you need to pass a string to explode() so try with implode() use limit -1 to get first array of explode
$pid = explode('=',implode('=',explode('&',$_SERVER['QUERY_STRING'],-1)));
else you need to two statement
$fr = explode('&',$_SERVER['QUERY_STRING']);
$pid = explode('=',$fr[0]);
Dreamweaver does'n recognise PHP 5.4, and as Michael stated, this expression is only correct since version 5.4