Multidimensional array undefined index problem - php

I am getting a multidimensional array from an HTML form. When I want to get a single value, e.g.
$chapters = $_POST["chapters"];
echo $chapters[0]["title"];
it says undefined index title.
When I print the array, it shows as
Array
(
[chapters] => Array
(
[0] => Array
(
['title'] => this is title
['text'] => this is text
['photo'] => this is photo source
['photo_caption'] => photo caption
)
)
)

Based on your comments, the problem seemed to be following:
print_r never prints quotes for string keys. If you have not manipulated the output somehow, then it can only mean that the single quotes are actually part of the key.
This should work:
echo $chapters[0]["'title'"];
but better you fix the keys.
From your comment:
the problem was that i was using single quotes (name="chapter[0]['photo_caption']") in html form, corrected to name="chapter[0][photo_caption]" solved the problem

According to your output, you should be using $chapters["chapters"][0]["title"].
Note that you have 3 nested arrays in your output, therefore you'll need to go 3 levels deep to get your value.

Yeah, I faced the same problem. Then I realized, I was doing wrong with the keys.
Actually, I was using the quote while naming the form elements as an array
Example-
echo "<input type='hidden' name= userprogramscholarship[$user->id]['checkstatus'] value= $val />";
I corrected and removed quotes as below
echo "<input type='hidden' name= userprogramscholarship[$user->id][checkstatus] value= $val />";
It was minor mistake. Removed quotes and it worked then.

Related

Unserialize not working for multi-dimensional array

So I have run into this problem many times before, but I would always get around it using base64_encode/decode and that would get it working right away.
However, in this application I cannot use that, because I need to be able to query this field and I wouldn't know how I could do that if it was encoded.
Pardon my ignorance, but is there a way to unserialize a multi-dimensional array without using base64 encoding?
Update 1
Removing the strings and turning them to integers fixes the problem. So it is either a problem with strings, or I suspect the " is causing issues. Anyway to work around that?
For this application, the second element of the array represents a date in a format that it would be searched under. Ideally, I would like to leave that as is, but if it is necessary I suppose I can use an integer to represent the number of days away from a constant, and then interpret that result.
Below is the code:
// Load Contact from Database
$returnFields = array('_AttendanceRecords');
$Contact = $app->loadCon(39732,$returnFields);
echo "<pre>";
print_r($Contact);
echo "</pre>";
echo $Contact['_AttendanceRecords'] . "</br>";
// To unserialize...
$AttendanceRecordsLoad = unserialize($Contact['_AttendanceRecords']);
echo "<pre>";
print_r($AttendanceRecordsLoad);
echo "</pre>";
Output is:
Array (
[_AttendanceRecords] => a:1:{i:0;a:3:{i:0;i:1;i:1;s:10:"10-09-2015";i:2;s:1:"1";}} )
a:1:{i:0;a:3:{i:0;i:1;i:1;s:10:"10-09-2015";i:2;s:1:"1";}}
As you can see, the final print_r comes out empty, which I believe is returning false for whatever reason.
Update 2
So after more fiddling around, I made this new code:
Code
$ContactId = 39732;
$returnFields = array('_AttendanceRecords');
$Contact = $app->loadCon($ContactId,$returnFields);
echo $Contact['_AttendanceRecords'] . " - IS result </br>";
echo $str = 'a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}}'; echo " - str result </br>";
// To unserialize...
$AttendanceRecordsLoad = unserialize($Contact['_AttendanceRecords']);
$AttendanceRecordsLoad1 = unserialize($str);
echo "IS<pre>";
print_r($AttendanceRecordsLoad);
echo "</pre>";
echo "str<pre>";
print_r($AttendanceRecordsLoad1);
echo "</pre>";
Output
a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}} - IS result
a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}} - str result
IS
str
Array (
[0] => Array
(
[0] => 0
[1] => 10-10-15
[2] => 1
)
)
I don't understand. The strings appear identical. Yet the result that comes from the database won't unserialize if it contains a string.
Does that make sense to anyone?
Update 3
Ok, so now I used var_dump instead of echo and I get this outputted:
Output
string(61) "a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}}" - IS
result
string(51) "a:1:{i:0;a:3:{i:0;i:0;i:1;s:8:"10-10-15";i:2;i:1;}}" - str result
So obviously they are not identical. But I tried trim before, and now, and it doesn't remove any hidden extra characters that somehow have lodged themselves in to this string.
What does that mean and how do I correct this?
Ok figured it out by looking at this question:
SOLUTION FOUND - Same strings, but var_dump() says one is 5 characters longer
The fix was using this on the returned result from the database:
html_entity_decode($string], ENT_QUOTES)
Hope that helps someone else too.

Array Not Returning Entire Element

I think I simply have invalid syntax, but for the life of me I can't figure it out. I have a nested array with 3 elements.
$screenshot = array( array( Carousel => "Library.png", Caption => "Long caption for the library goes here", ListItem => "The Library"));
I'm using a for loop to compose some HTML that includes the elements.
<?php
for ( $row = 0; $row < 4; $row++)
{
echo "<div class=\"feature-title\">" . $screenshot[$row]["ListItem"] . "</div>";
}
?>
My problem is that the "title" portion of the "a" tag only includes the first word, Long. So in the above case it would be:
<div class="feature-title">The Library</div>
Can anyone shed some light on my error? Thanks in advance.
You forgot double quotes around the attribute values, so only the first word counts. The rest become (invalid) attribute names.
Make a habit of wrapping, the array index within double-quotes i.e. " for string indexes.
$screenshot = array(
array(
"Carousel" => "Library.png",
"Caption" => "Long caption for the library goes here",
"ListItem" => "The Library")
);
As Starx and Ignacio have mentioned, the key parts of the arrays need to be quoted. It doesn't matter if they are single or double quotes though. If you turn on more verbose logging (like E_ALL instead of E_ALL & ~E_NOTICE) you'll get messages like this:
PHP Notice: Use of undefined constant Carousel - assumed 'Carousel' in badarray.php on line 3
PHP Notice: Use of undefined constant Caption - assumed 'Caption' in badarray.php on line 3
PHP Notice: Use of undefined constant ListItem - assumed 'ListItem' in badarray.php on line 3
PHP tries to find a constant that has been defined with those names. When it cannot find one it assumes you meant the string of that value. This means that if you ever did define a constant named "Carousel", "Caption" or "ListItem" it would change the key values in the array you defined.
The other issue I see, and it could just be that only partial code was included, was there is only a single array inside of the outer array so when you're accessing $screenshot[$row], there will be nothing there once your loop increments $row beyond 0.
If you can provide what you're trying to output from using that array, I can help you build that code.
please use this code
echo "<div class=\"feature-title\">" . $screenshot[$row]["ListItem"] . "</div>";

PHP: Strange Array Problem - Where is my value?

I have an array ($form) which retreives some information from $_POST:
$form = $_POST['game'];
Now I want to work with the values in this array, but I somehow fail.
For debugging I used these commands (in the exact same order, with no extra lines inbetween):
print_r($form);
echo '#' . $form['System_ID'] . "#";
and as returned output I get:
Array
(
['Title'] => Empire: Total War - Special Forces
['Genre_ID'] => 1
['Type'] => Spiel
['System_ID'] => 1
)
##
Any ideas where my System_ID went? It's there in print_r, but not in the next line for echo?!?
Alright, I found the solution myself (a.k.a. d'oh!)
I added another
var_dump($form);
for further analysis and this is what I got:
array(4) {
["'Title'"]=>
string(34) "Empire: Total War - Special Forces"
["'Genre_ID'"]=>
string(1) "1"
["'Type'"]=>
string(5) "Spiel"
["'System_ID'"]=>
string(1) "1"
}
Notice the single quote inside the double quote?
Looks as if you're not allowed to use the single quote in html forms or they will be included in the array key:
Wrong: <input type="text" name="game['Title']" />
Correct: <input type="text" name="game[Title]" />
print_r() doesn't put quotes around keys - for debugging i'd recommend ditching print_r altogether. var_export or var_dump are better.
even better: use firephp. it sends the debug info via headers, so it doesn't mess up your output and thus is even usable with ajax. output is displayed nicely with firebug including syntax coloring for data structures.
and it's even easier to use: just fb($myvar);
It works for me:
<?
$form['System_ID'] = 1;
print_r($form);
echo '#' . $form['System_ID'] . '#';
?>
Output:
% php foo.php
Array
(
[System_ID] => 1
)
#1#
PHP 5.2.6, on Fedora Core 10
EDIT - note that there's a hint to the real cause here. In my code the print_r output (correctly) shows the array keys without single quotes around them. The original poster's keys did have quotes around them in the print_r output, showing that somehow the actual key contained the quote marks.

How do I access a string-indexed element of a PHP array?

I have the following array (in php after executing print_r on the array object):
Array (
[#weight] => 0
[#value] => Some value.
)
Assuming the array object is $arr, how do I print out "value". The following does NOT work:
print $arr->value;
print $val ['value'] ;
print $val [value] ;
So... how do you do it? Any insight into WHY would be greatly appreciated! Thanks!
echo $arr['#value'];
The print_r() appears to be telling you that the array key is the string #value.
After quickly checking the docs, it looks like my comment was correct.
Try this code:
print $arr['#value'];
The reason is that the key to the array is not value, but #value.
You said your array contains this :
Array (
[#weight] => 0
[#value] => Some value.
)
So, what about using the keys given in print_r's output, like this :
echo $arr['#value'];
What print_r gives is the couples of keys/values your array contains ; and to access a value in an array, you use $your_array['the_key']
You might want to take a look at the PHP manual ; here's the page about arrays.
Going through the chapters about the basics of PHP might help you in the future :-)

Php $_GET issue

foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
}
print_r($datarray);
This is the output I am getting. I see the data is there in datarray but when
I echo $_GET[$field]
I only get "Array"
But print_r($datarray) prints all the data. Any idea how I pull those values?
OUTPUT
Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
EDIT: When I completed your test, here was the final URL:
http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24
This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:
http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan&region=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24
This will create individual entries for most of the fields, and make $_GET['answer'] be an array of the answers provided by the user.
Bottom line: fix your Flash file.
Use var_export($_GET) to more easily see what kind of array you are getting.
From the output of your script I can see that you have multiple nested arrays. It seems to be something like:
$_GET = array( array( array("Grade1", "ln", "North America", "yuiyyu", "iuy", "uiyui", "yui","uiy","0:0:5")))
so to get those variables out you need something like:
echo $_GET[0][0][0]; // => "Grade1"
calling echo on an array will always output "Array".
print_r (from the PHP manual) prints human-readable information about a variable.
Use <pre> tags before print_r, then you will have a tree printed (or just look at the source. From this point you will have a clear understanding of how your array is and will be able to pull the value you want.
I suggest further reading on $_GET variable and arrays, for a better understanding of its values
Try this:
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo $_GET[$field]; // you don't really need quotes
echo "With quotes: {$_GET[$field]}"; // but if you want to use them
echo $field; // this is really the same thing as echo $_GET[$field], so
if($label == $_GET[$field]) {
echo "Should always be true<br>";
}
echo "<br>";
}
print_r($datarray);
It's printing just "Array" because when you say
echo "$_GET[$field]";
PHP can't know that you mean $_GET element $field, it sees it as you wanting to print variable $_GET. So, it tries to print it, and of course it's an Array, so that's what you get. Generally, when you want to echo an array element, you'd do it like this:
echo "The foo element of get is: {$_GET['foo']}";
The curly brackets tell PHP that the whole thing is a variable that needs to be interpreted; otherwise it will assume the variable name is $_GET by itself.
In your case though you don't need that, what you need is:
foreach ($_GET as $field => $label)
{
$datarray[] = $label;
}
and if you want to print it, just do
echo $label; // or $_GET[$field], but that's kind of pointless.
The problem was not with your flash file, change it back to how it was; you know it was correct because your $dataarray variable contained all the data. Why do you want to extract data from $_GET into another array anyway?
Perhaps the GET variables are arrays themselves? i.e. http://site.com?var[]=1&var[]=2
It looks like your GET argument is itself an array. It would be helpful to have the input as well as the output.

Categories