Using .= to add to an array in PHP 5.3 - php

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);

Related

Warning: Attempt to read property "[ARRAY KEY]" on null in PHP

$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.

Unable to get dynamic PHP's Object value using PHP variable

PHP is unable to get the value for dynamic object prepared as:
$abc->{$dynamic_object_pattern}
Where the value of the variable $dynamic_object_pattern is, json->{'data_1'}->{'value'}
For me, PHP 7.1 is understanding the statically defined pattern like below, and fetching the value as it should:
$abc->json->{'data_1'}->{'value'}
But not when I put the whole portion into a variable and then try to get its value. I Tried,
$abc->{$dynamic_object_pattern} and $abc->$dynamic_object_pattern
both ways, but no solution yet.
The error comes is Notice: Undefined property: stdClass::$json->{'data_1'}->{'value'}
I'm attempting an answer without seeing your JSON data
Here you say :
But not when I put the whole portion into a variable and then try to
get its value
From that line alone it sounds like you are trying to get value from a string rather than array. If you put the whole portion into a variable, PHP will interpret it as string. Make sure you add array() before newly created variable.
Natural array :
$array = array();
Now a string
$variable = $array;
Convert string to array
$new_array = array($variable);
Also, have you tried decoding?
// decode
$response = json_decode($new_array, true);
//print out
var_export(array_unique(array($response)));

best way append named array to array in PHP 5.2

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']";

Checking for empty attributes while parsing an XML file

A critical function in a PHP script I am debugging get's two attributes from an XML file on an external site. The attributes are labeled 'code' and 'locationCode' within a tag called Channel. The issue is that sometimes the locationCode is posted as an empty string ('') or not defined at all by the site for channels I cannot use, so I need to loop through the channels until I find a non-empty locationCode string. To do this, I created a while loop, but my current implementation does not successfully loop through the location codes. Is there a better way to implement this?
Current code:
public function setChannelAndLocation(){
$channelUrl="http://service.iris.edu/fdsnws/station/1/query?net=".$this->nearestNetworkCode.
"&sta=".$this->nearestStationCode."&starttime=2013-06-07T01:00:00&endtime=".$this->impulseDate.
"&level=channel&format=xml&nodata=404";
$channelXml= file_get_contents($channelUrl);
$channel_table = new SimpleXMLElement($channelXml);
$this->channelUrlTest=$channelUrl;
//FIXME: Check for empty locationCode string
$this->channelCode = $channel_table->Network->Station->Channel[0]['code'];
$this->locationCode = $channel_table->Network->Station->Channel[0]['locationCode'];
$i = 1;
while($this->locationCode=''){
$this->channelCode = $channel_table->Network->Station->Channel[$i]['code'];
$this->locationCode = $channel_table->Network->Station->Channel[$i]['locationCode'];
$i++;
}
}
sample XML file for code: http://service.iris.edu/fdsnws/station/1/query?net=PS&sta=BAG&starttime=2013-06-07T01:00:00&endtime=2013-10-12T18:47:09.5000&level=channel&format=xml&nodata=404
There are two problems I can see with this line:
while($this->locationCode=''){
Firstly, you have typed an assignment (=) when what you wanted was a comparison (==). So instead of testing the condition, this line is over-writing the current value of $this->locationCode and then testing the "truthiness" of '', which evaluates to false, so the while loop never runs.
Secondly, the sample XML file shows that the attribute is not in fact empty, but contains some whitespace. Assuming these are the values you want to ignore (there are none in the sample right now which have any other value), you can use trim() to eliminate the whitespace from the comparison, giving you this:
while( trim($this->locationCode) == '' ) {

Get Data from Array by Variable

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.

Categories