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>";
Related
I would like to use the first value of a dynamically created array but I get the first letter of the array name instead.
$log = "dets_".$id;
$$log = array();
while ($c = mysql_fetch_assoc($cuenta)) { array_push($$log,$c['id'].'::'.$c['fecha']); }
When I print $$log I get something like this:
Array ( [0] => 124::2017-04-07 [1] => 119::2017-04-07 [2] => 118::2017-04-05 )
But when I try to access the first key:
echo $$log[0];
I get "$d" and not "124::2017-04-07". I also tried $log[0] and get "d".
Thank you.
You could access the first element by somewhat tricky expression:
var_dump (${${'log'}}[0]);
http://php.net/manual/en/language.variables.variable.php
A bit of explanation Taken from PHP Manual
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you write $$a[1] then the parser needs
to know if you meant to use $a[1] as a variable, or if you wanted $$a
as the variable and then the [1] index from that variable. The syntax
for resolving this ambiguity is: ${$a[1]} for the first case and
${$a}[1] for the second.
can anyone help me please. In a loop, I get a list with page titles from an external website. And these titles are unknown strings. Every Page title has a name and a ID like "NAME X - PRJ12345".
the title are saved in $title_mainpage
And I want to save the String Part "NAME X" in variable $title_name and the unknown ID of the String in variable $title_id.
Every title are different, but the ID has always the same length - start with "PRJ" + 5 numbers.
I hope the question is clear. Thanks in advance!!
$x='NAME X - PRJ12345';
$arr=explode('-',$x);
$title_name=echo $arr[0];
$title_id=echo $arr[1];
You can do this by using list and explode functions. list actually assign variables to the values as they were in arrays. While explode break the string into array. With the help of list you don't need to use arrays explicitly.
$variable = "NAME X-PRJ12345";
list($title_name, $title_id) = explode('-', $variable);
echo $title_name . "<br>";
echo $title_id;
Possible output will be like this:
NAME X
PRJ12345
For deep information you can see documentation for list and explode
I have a problem with this code:
$a['i'] = 1;
$b = '$a[\'i\']';
echo $$b;
It display an error:
Notice: Undefined variable: $a['i'] in test.php on line 6
Is it possible to create dynamic array variable?
Thanks for your time.
EDIT: In my example I am trying to edit an multidimensional array. There is a problem when I try to add data to my array (JSON). I don't have fixed dimension of array, it my be 2 or more dimension (I am building a model for Web form, and I want to add invalid value to JSON).
Now in one of the methods of Web form object I have code which checks repopulation object to add invalid value if needed.
I can not just add a value to JSON array, I need to edit it on multidimensional level.
For now I came up on solution to dynamically generate variable name and, then, edit it. If someone have solution it will be appreciated.
private $form = array(
'form_contact'=>array(
'attr'=>array('tag'=>'FORM', 'method'=>'post'),
'elem'=>array(
'fs_contact'=>array(
'attr'=>array('legend'=>'Kontakt', 'tag'=>'FSET'),
'elem'=>array(
'name'=>array(
'attr'=>array('SPAN'=>'Ime i prezime', 'title'=>'Unesite Vaše ime i prezime', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('req'=>'noscript', 'length'=>255),
'invalid'=>true), // Holds info that this is invalid
'www'=>array(
'attr'=>array('SPAN'=>'Web sajt', 'title'=>'Unesite Vaš sajt', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('length'=>255)),
'email'=>array(
'attr'=>array('SPAN'=>'E-mail', 'title'=>'Unesite Vaš email', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('req'=>'email', 'length'=>255)),
'message'=>array(
'attr'=>array('SPAN'=>'Poruka', 'cols'=>'60', 'rows'=>'5', 'title'=>'Unesite Vašu poruku', 'tag'=>'TEXTA', 'value'=>'nesto'),
'validat'=>array('req'=>'all')),
'submit_new_contact_form'=>array(
'attr'=>array('tag'=>'INPUT', 'type'=>'submit', 'value'=>'Pošalji poruku!'))
))// FS end
)) // Form end
);// Array end
You can't do it that way, as PHP thinks you're looking for a variable with the name $a['i'], rather than the 'i' key in the $a array.
The proper, and conventional, way is to use a dynamic key/index instead:
$b = 'i';
echo $a[$b];
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.
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.