PHP Associative Array - php

PHP
<?php
$truck['Toyota']=Tundra;
$truck['Nissan']=Titan;
$truck['Dodge']=Ram;
print "<br />Toyota makes the".$truck['Toyota']."<br />";
print "Nissan makes the".$truck['Nissan']."<br />";
print "Dodge makes the".$truck['Dodge']."<br />";
?>
I am learning PHP by tutorial:
An Associative Array is an array in which the keys are associated with values.
And, when viewed in a browser...
Toyota makes the Tundra
Nissan makes the Titan
Dodge makes the Ram
NOT SO!
I get:
Toyota makes theR
Nissan makes theR
Dodge makes theR
Can anyone explain?

OK so everyone has pointed out that you need to quote your strings, but that's not the real problem.
(The reason that your code is not throwing an error right now is because the strings you forgot to quote are treated as PHP "bare strings" -- basically an undefined constant whose name is used as the value, you should not use/rely on this.)
Now for the real problem: it looks like you have already defined $truck to be a string further up in your code, so when you try to read/write to it as if it were an associative array, you are really read/writing the first character in that originally defined string (the string key your are using is converted to an int). Since the last assignment is $truck['Dodge'] = "Ram", the first character in $truck is changed to an "R", and that's what you are then seeing in your output.
You should (and this case need to) define $truck as an array before you start using it like one:
$truck = array();
$truck['Toyota'] = "Tundra";
$truck['Nissan'] = "Titan";
$truck['Dodge'] = "Ram";
Even better, for best practices, you should use a different variable name for the first $truck (string) and the second $truck (array) so it's not confusing:
// some code that I imagine comes before your example
$truck = "Ford F150";
// ...
$trucks = array();
$trucks['Toyota'] = "Tundra";
$trucks['Nissan'] = "Titan";
$trucks['Dodge'] = "Ram";
print "<br />Toyota makes the".$trucks['Toyota']."<br />";
print "Nissan makes the".$trucks['Nissan']."<br />";
print "Dodge makes the".$trucks['Dodge']."<br />";

You need quotes around string literals. E.g.:
<?php
$truck['Toyota'] = "Tundra";
$truck['Nissan'] = "Titan";
$truck['Dodge'] = "Ram";
A good idea is to enable error reporting, so you will be told about these issues by the php interpreter. Stick this line at the top of your script (next after <?php):
error_reporting(E_ALL);

It looks like you're using constants Tundra Titan and Ram instead of strings. Have you defined those constants elsewhere in your code?

$truck['Toyota']="Tundra";
$truck['Nissan']="Titan";
$truck['Dodge']="Ram";
I think its a syntax error.

you have to put your strings inside quotation marks:
$truck['Toyota']='Tundra';
$truck['Nissan']='Titan';
$truck['Dodge']='Ram';

I don't know if the post has been edited by Stack Overflow or it lost them but your values are not wrapped in single quotations..
Also, just a piece of advice; concatenation is only required on single quote strings you can wrap your variables in braces to save that 0.00001 msec :)

Enable error reporting and reduce the code to more quickly fix if you've found the error:
<?php
# display errors and show all warnings and errors, that's helpful:
ini_set('display_errors', 1); error_reporting(~0);
$truck['Toyota']=Tundra;
$truck['Nissan']=Titan;
$truck['Dodge']=Ram;
echo "<br />\n";
# when doing the same thing multiple times, take foreach:
foreach ($truck as $manufacturer => $model)
{
echo $manufacturer, ' makes the ', $model, ".<br />\n";
}

Related

Unable to produce variable output of type string in multi-lines in PHP

I don't know the correct wording for this issue I am having.
I have a object returned from the database like below:
$pProvisioningFileData->m_fileContent = # Placeholders identified by '${}'
will be replaced during the provisioning
# process, only supported placeholders will be processed.
Dcm.SerialNumber = ${unit.serial_number}
Dcm.MacAddress = ${unit.mac_address}
Dcm.MinSeverity = "Warning"
Cert.TransferHttpsCipherSuite = "CS1"
Cert.TransferHttpsTlsVersion = "TLSv1"
Cert.MinSeverity = "Warning";
The curly brackets are placeholders, the problem I am facing is that when I try output all the content using either echo or print_r, all the content prints in one line however I want to display the content in the same sequence as above.
I tried using var_dump but it also gives some extra info like length and type of variable which I don't want.
So is there a simple way of doing this without using an array?
If you are outputting to browser then wrapping your var_dump in html <pre> tags is quick solution. If you outputting to console then I advise you to install some advanced debuging software. Xdebug comes to mind.
It is difficult from your question to understand exactly what you are wanting to do, but there are three ways you can print out the contents of an object. The third here, looping members, will give you more control and you can add a switch statement or other formatting to output precisely what you desire:
class unit {
var $serial_number;
var $mac_address;
}
$test = new unit;
$test->serial_number = "999";
$test->mac_address = "999.999.999.999";
/* Method 1 - print_r */
print_r($test);
print "\n\n";
/* Method 1 - var_dump */
var_dump($test);
print "\n\n";
/* Method 3 - looping members */
foreach ($test as $memberName => $member)
{
print "{$memberName}: {$member}\n";
}

Testing if a combined variable name exists

I am sure this has been asked 100 times but cannot find the form of words to get at the answer either here or on Google.
I have a variable number of messages. They arrive as
$_GET['message1']; $_GET['message2']; $_GET['messageX']; etc
where X can be 1 to 100.
I need to test if they exist and then push them out to a DB. I tried
$i=1;
while (isset(parse_str("message$i")))
{
echo parse_str("output=message$i");
echo "<h1>This is test $output </h1>";
$i++;
}
which does not work. I thought the middle part worked but just re-tested and that is wrong too.
I am new to parse_str(). I thought I understood it and I understand the problem (it is a void function so cannot be used as a test) but cannot work out a solution for getting through the variables.
parse_str parses a string. What do you expect in a string "message$i"?
If you're sure that all your messages come from $_GET, use $_GET:
$i = 1;
while (isset($_GET['message' . $i])) {
echo $_GET['message' . $i];
$i++;
}
But obviously for storing such data, arrays are move convenient.

php foreach in foreach looping

I want to extrect all usernames and passwords each from his file and output it nicely.
I wrote a code on my appserv 2.5.1 on my computer but only the last loop gave the username output.
Tested the code on other machines and it worked perfectly.
Dont know what is the problem ...
usernames.txt content :
user1
user2
user3
passwords.txt content :
pass1
pass2
pass3
script content :
$usernames = explode("\n", file_get_contents("usernames.txt"));
$passwords = explode("\n", file_get_contents("passwords.txt"));
foreach( $usernames as $username )
{
foreach( $passwords as $password )
{
echo $username.":".$password."\n";
}
}
output :
:pass1
:pass2
:pass3
:pass1
:pass2
:pass3
user3:pass1
user3:pass2
user3:pass3
for ($i=0;$i<count($usernames) && $i<count($password); $i++) {
echo $usernames[$i].':'.$passwords[$i];
}
But $password[x] must be related to $usernames[x]
There's always those that will say you don't need it (and you often don't) but I tend to use regular expressions whenever I'm parsing these kind of flat files - there's always some quirky character, extra line-break or difference that finds it's way into a text file - be it from transferring servers, restoring backups or simply user-interference. You could also make use of array_combine in this situation if you'd prefer to carrying on using a foreach loop - I know some folks prefer it for readability.
preg_match_all('/\w+/m', file_get_contents('usernames.txt'), $usernames);
preg_match_all('/\w+/m', file_get_contents('passwords.txt'), $passwords);
if(count($usernames[0]) !== count($passwords[0]))
die('Computer says: mismatch!'); // some resemblance of error handling...
$result = array_combine($usernames[0], $passwords[0]);
foreach($result as $name => $pass)
echo "{$name}:{$pass}\n";
demo
After debugging with the post author, I guessed that the problem was with the line return character. Using a \r\n fixed the problem:
$usernames = explode("\n\r", file_get_contents("usernames.txt"));
$passwords = explode("\n\r", file_get_contents("passwords.txt"));
For reference, please note that it is very important not to assume your input data is right. If you see that something is wrong and it points obviously to a mistake you made previously (in that case it is clearly not the foreach function that is buggy, but the array), then you need to swallow your pride and debug your own code. I have been programming PHP for 10 years, and I still have to remember that every single day.

PHP EOF showing only one result [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
PHP EOF shows only one result from loop
Hello
Seems like I can not find the solution for such problem.
I am using the following code.
it should display all the results given by the mySQL loop in the EOF.
But it is showing only the first results, nothing else.
What I am doing wrong?
Please help me
function getYiBAdminBanner() {
global $site;
global $dir;
$queryYiBmenu = "SELECT * FROM `(YiB)_cPanel_Menu` WHERE Type = 'top'";
$resultYiBmenu=mysql_query($queryYiBmenu) or die("Errore select menu: ".mysql_error());
$countYiBmenu = mysql_num_rows($resultYiBmenu);
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
$menu .= "<div id=\"menu\" style=\"display:none;\"><li><img class=\"imgmenu\" src=\"".$site['url'].$rowYiBmenu['linkIcon']."\">".$rowYiBmenu['linkTitle']."</li></div>";
}
if($countYiBmenu <= 0){
$menu = "No Modules Installed";
}
$bannerCode .= <<<EOF
<div style="width:520px; background-color: #EEE; height:30px;">
{$menu}
</div>
EOF;
return $bannerCode;
}
Though this won't fix your issue, I see you are using mysql_fetch_array(). This is rather pointless, as you are doing associative matching afterwards ($rowYiBmenu['linkHref'], for example). It will work for you, but it's a waste of resources, as the results will be loaded in a numeric array as well (making the $rowYiBmenu array twice as large, just wasting memory).
Also, you didn't declare the $menu variable, you just 'added on'. Before the while statement, put $menu = ''; (or anything else that will declare an empty string for that variable).
Lastly, use single quotes around html strings. That way you don't have to keep escaping double quotes for when adding an attribute. For example, the $menu line in the while statement should look like this:
$menu .= '<div id="menu" style="display:none;"><li><img class="imgmenu" src="'.$site['url'].$rowYiBmenu['linkIcon'].'">'.$rowYiBmenu['linkTitle'].'</li></div>';
I'm not sure if I helped you with your problem at all, but I thought this would help you clean up your code a bit (the cleaner the code, the less prone to errors and the easier it is to spot errors).
I have tried helping in the other duplicate question.
i feel you need to implement (learn?) some basic debugging on the data coming from the database. This should be very simple to solve.
I suggest changing your while() code to something like this to help debug whats happening:
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
print "linkTitle: " . $rowYiBmenu['linkTitle'] ."<BR>";
print "linkHref: " . $rowYiBmenu['linkHref'] ."<BR><BR>";
}
exit;
You should see output of all results from the database (not just the first or last). After establishing that the correct data is being retrieved and looped through. you can get that $menu variable concatenation and $bannerCode + HereDoc EOF code sorted out.

PHP preg_replace problem

This is a follow-up question to the one I posted here (thanks to mario)
Ok, so I have a preg_replace statement to replace a url string with sometext, insert a value from a query string (using $_GET["size"]) and insert a value from a associative array (using $fruitArray["$1"] back reference.)
Input url string would be:
http://mysite.com/script.php?fruit=apple
Output string should be:
http://mysite.com/small/sometext/green/
The PHP I have is as follows:
$result = preg_replace('|http://www.mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
This codes outputs the following string:
http://mysite.com/small/sometext//
The code seems to skip the value in $fruitArray["$1"].
What am I missing?
Thanks!
Well, weird thing.
Your code work's perfectly fine for me (see below code that I used for testing locally).
I did however fix 2 things with your regex:
Don't use | as a delimiter, it has meaning in regex.
Your regular expression is only giving the illusion that it works as you're not escaping the .s. It would actually match http://www#mysite%com/script*php?fruit=apple too.
Test script:
$fruitArray = array('apple' => 'green');
$_GET = array('size' => 'small');
$result = 'http://www.mysite.com/script.php?fruit=apple';
$result = preg_replace('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
echo $result;
Output:
Rudis-Mac-Pro:~ rudi$ php tmp.php
http://www.mysite.com/small/sometext/green/
The only thing this leads me to think is that $fruitArray is not setup correctly for you.
By the way, I think this may be more appropriate, as it will give you more flexibility in the future, better syntax highlighting and make more sense than using the e modifier for the evil() function to be internally called by PHP ;-) It's also a lot cleaner to read, IMO.
$result = preg_replace_callback('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#', function($matches) {
global $fruitArray;
return 'http://www.mysite.com/' . $_GET['size'] . '/sometext/' . $fruitArray[$matches[1]] . '/';
}, $result);
i write it again, i don't understand good where is the error, the evaluation of preg results is very weird in php
preg_replace(
'|http\://([\w\.-]+?)/script\.php\?fruit=([\w_-]+)|e'
, '"http://www.$1/".$_GET["size"]."/sometext/".$fruitArray["$2"]."/";'
, $result
);
It looks like you have forgotten to escape the ?. It should be /script.php\?, with a \? to escape properly, as in the linked answer you provided.
$fruitArray["\$1"] instead of $fruitArray["$1"]

Categories