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.
Related
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)));
Why is the following code failing to store the entire strings from the "name" column into my output array? The code did work at some point.
$contacts = "";
$sql = "SELECT * FROM s_issue.t_contact WHERE orgid='$orgid' ORDER BY id";
$results = db_query($db, $sql, "psql");
while($row = pg_fetch_assoc($results)){
$contacts[$row["id"]] = $row["name"];
}
return $contacts;
The database column id contains integers, and the name column contains strings. The expected output was a list of contact names, but in my initial trials, I was getting a blank list.
I was asked to look at some very old legacy code. It was non-obvious as to the recency of the upgrade to PHP7, and when I started looking I wasn't even sure it was PHP7.
In case you come across some legacy code like this, and find yourself wondering why the output array does not contain what you expect, have you recently upgraded to PHP7? Because that's the cause.
The initial line in PHP7 now coercively (default) types $contacts as a string. Further, a string can be indexed numerically to access each character in that string. That is:
$foo = "abcde";
echo $foo[1]; // outputs 'b'
So when $row["id"] is numeric, then $contacts[$row["id"]] becomes a string with a numeric index. Hence, only one character can be stored at that location, and it is the first character of the string $row["name"].
The proper fix is to either remove the wrongly-typed initialization line of $contacts = "" completely, or correctly initialize it to the type actually desired, an array:
$contacts = array();
The code in question worked fine before PHP7. It will fail in mysterious ways in PHP7.
I have dynamically created an array and I want to extract the array and put each item into its own variable.
Here's my PHP:
$bar = $_POST['foo'];
extract($bar);
echo $1;
foo is an array from a form I made.
Whenever I run the script I get this error:
Parse error: syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '$' in /Application/...
When I change my code to:
$bar = $_POST['foo'];
extract($bar, EXTR_PREFIX_ALL, "bar_");
echo $bar_1;
I get the undefined variable error.
Please help me.
UPDATE:
My first code was informational, another person might come across this question with that problem not knowing what's wrong. The second piece of code is my actual code.
M intention is to input each array item into a different field in a mysql table. I haven't written the full code yet since this extract() thing doesn't seem to be working.
UPDATE 2:
$_POST['foo'] is an array of checkbox values
Variables in PHP cannot start with numbers:
echo $1;
That's invalid and will throw an error.
You're also using extract improperly in that you're using it on something that may or may not be an array. We have no guarantee that $_POST['foo'] is an associative array(and it's not), which is the only array type extract works on. extract uses the keys from the associative array to create the new variables.
$bar = $_POST['foo'];
extract($bar, EXTR_PREFIX_ALL, "bar_");
echo $bar_1;
From http://php.net/extract
Prefixes are automatically separated from the array key by an underscore character.
Your extracted variable is named $bar__1 (two underscores).
But listen to everyone who answered, "do not use extract() on untrusted data."
This is very unsafe.
You should not do it.
foreach($_POST['foo'] as $key=>$value) {
${"itemnumber".(string)$key} = $value;
}
Now you can acces $itemnumber2 ---> equals to the array item in the position 2
EDIT: I just tested it at writecodeonline.com and it works:
$arr = array('one', 'two');
foreach($arr as $key=>$value) {
${"itemnumber".(string)$key} = $value;
}
echo $itemnumber1; //echoes: two
Here you can see a similar case:
http://us2.php.net/manual/en/function.extract.php#60946
In my form i have fields with name photoid[] so that when sent they will automatically be in an array when php accesses them.
The script has been working fine for quite some time until a couple days ago. And as far as i can remember i havent changed any php settings in the ini file and havent changed the script at all.
when i try to retrieve the array using $_POST['photoid'] it returns a string with the contents 'ARRAY', but if i access it using $_REQUEST['photoid'] it returns it correctly as an array. Is there some php setting that would make this occur? As i said i dont remember changing any php settings lately to cause this but i might be mistaken, or is there something else i am missing.
I had the same problem. When I should recieve array via $_POST, but var_dump sad: 'string(5) "Array"'. I found this happens, when you try use trim() on that array!
Double check your code, be sure you're not doing anything else with $_POST!
Raise your error_reporting level to find any potential source. It's most likely that you are just using it wrong in your code. But it's also possible that your $_POST array was mangled, but $_REQUEST left untouched.
// for example an escaping feature like this might bork it
$_POST = array_map("htmlentities", $_POST);
// your case looks like "strtoupper" even
To determine if your $_POST array really just contains a string where you expected an array, execute following at the beginning of your script:
var_dump($_POST);
And following for a comparison:
var_dump(array_diff($_REQUEST, $_POST));
Then verifiy that you are really using foreach on both arrays:
foreach ($_POST["photoid"] as $id) { print $id; }
If you use an array in a string context then you'll get "Array". Use it in an array context instead.
$arr = Array('foo', 42);
echo $arr."\n";
echo $arr[0]."\n";
Array
foo
$_POST['photoid'] is still an array. Just assign it to a variable, and then treat it like an array. ie: $array = $_POST['photoid'];
echo $array[0];
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.