I have a simple php code which changes the order of the name inside an array.
$arr = [
"Meier, Peter",
"Schulze, Monika",
"Schmidt, Ursula",
"Brosowski, Klaus",
];
foreach($arr as $name => $name2)
{
$vname = explode(", ", $name2);
$new = array_reverse($vname);
$arr[$name] = implode(", ", $new);
}
echo "<pre>".print_r($arr, true)."</pre>";
Basically I would like the edit the code, that the source code displays the array not in one line, but in several lines (one for each Firstname + Lastname) like shown below:
Array
(
[0] => Peter, Meier
[1] => Monika, Schulze
[2] => Ursula, Schmidt
[3] => Klaus, Brosowski
)
Right now the source code shows the excelpt same result, but only in one line. Is it possible to adapt the print_r command in this way?
Best Regards
Edit for clarification:
my code gives as a result the array which I have also posted in my question. In the html source code, the same array is in one line[0] => Peter, Meier [1] => Monika, Schulze and so on. So there is a difference between the way my result is structured and how the source code is structured. I would like to change the source code structure of the array, that it looks like the actual result.
You can adopt the line_breaks from print_r for html with the function nl2br()
echo nl2br(print_r($arr, true));
or you build a List function with
echo '<ul>'.PHP_EOL;
foreach($arr as $name){
echo "<li>{$name}</li>".PHP_EOL;
}
echo '</ul>'.PHP_EOL;
I think I found out what you were trying to say:
output is based on https://3v4l.org/LLvZW from #tcj
When printing with print_r your output looks like this:
When you inspect your HTML elements in your browser your inspector shows this:
(Note: everything is in one line)
The clarifications:
the output looks like this because <pre> does set a fixed width, and white-space: pre;
If you remove white-space: pre; you should end with an output like this:
If you inspect your element in the browser, it will still all be in one line
HOWEVER, if you try to edit the element inside your browser inspector then it WON'T be in one line.
So my answer to this is, that I assume this is some optimization done by the browser.
Probably so you can see more of the other HTML you have, or for other reasons...
(Im on Firefox btw.)
Related
I have a PHP variable $MostRecentQuestionType whose value is SimplifyingFractions. I want to print Simplifying Fractions, so I tried the following, but it returns Array ( [0] => Simplifyin [1] => Fractions )
$MostRecentQuestionType = $data['MostRecentQuestionType'];
$MostRecentQuestionTypeExploded = preg_split('/.(?=[A-Z])/',$MostRecentQuestionType);
print_r($MostRecentQuestionTypeExploded);
How do I extract the words from this array?
Side note: I know people are going to attack me for not doing my research; I've tried but I don't quite have the vocab to look up the solution. I've tried converting array to string and similar searches, but the results don't address this question. My searching has led to me to preg_replace, str_replace, toString(), among others, but nothing seems to help. I feel like I'm getting hung up on something that has a very easy solution.
Something like this:
<?php
$MostRecentQuestionType = "SimplifyingFractions";
$MostRecentQuestionTypeExploded = preg_split('/(?=[A-Z])/',$MostRecentQuestionType);
print(implode($MostRecentQuestionTypeExploded," "));
You could also cut out the middle man by doing:
<?php
$MostRecentQuestionType = "SimplifyingFractions";
$MostRecentQuestionTypeExploded = preg_replace('/(?=[A-Z])/'," ",$MostRecentQuestionType);
print($MostRecentQuestionTypeExploded);
Instead of your print_r command, you can do this :
foreach($MostRecentQuestionTypeExploded as $value) { print($value." ");}
I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];
I've been searching everywhere for a definitive answer to what seems to be a really simple task - unfortunately all the solutions I can find (and there are a lot) use mysql_fetch_assoc which is deprecated.
All I'm trying to do is to take a two column set of results from a database and echo in JSON format - I've managed everything fine except for one bit - I can't work how to get the values in to a two dimensional array (two column array) using array_push. I just end up with my two column values merged in to one array. Here's a stripped version of what I've done:
header('Content-Type: application/json');
$mostPopularStm = $sparklyGenericPdoObj->prepare("SELECT views, thing FROM X");
$mostPopularStm->execute();
$mostPopularRS = $mostPopularStm->fetchAll();
echo '{data:';
$mostPopularJson = array();
foreach ($mostPopularRS as $mostPopularItem)
{
array_push($mostPopularJson, $mostPopularItem["views"], $mostPopularItem["thing"]);
}
echo json_encode($mostPopularJson);
echo '}';
This is producing output like this:
{data:["Monkeyface","43","Giblets","25","Svelte","22","Biriani","21","Mandibles","20"]}
But what I need is this:
{data:["Monkeyface":"43","Giblets":"25","Svelte":"22","Biriani":"21","Mandibles":"20"]}
I know I can create something manually to do this, using json_encode to format the string on each loop but it seems inefficient.
Any pointers would be hugely appreciated!
Your current array is like
array(0 => 'Monkeyface', 1 => 43, /* ... */);
but you need like
array('Monkeyface' => 43, /* ... */);
Replace
array_push($mostPopularJson, $mostPopularItem["views"], $mostPopularItem["thing"])
By
$mostPopularJson[$mostPopularItem["thing"]] = $mostPopularItem["views"];
And
echo '{data:';
echo json_encode($mostPopularJson)
echo '}';
Better to use:
echo json_encode(array('data' => $mostPopularJson));
As kingkero said, you will never get your expected result because it is invalid:
{data:["Monkeyface":"43" ...
Correct:
{ "data": { "Monkeyface": "43" ...
Compose your array like so:
$mostPopularJson [$mostPopularItem["thing"]] = $mostPopularItem["views"];
When I run the following code:
echo $_POST['zipcode'];
print_r($lookup->query($_POST['zipcode']));
?>
the results are concatenated on one line like so: 10952Array.
How can I get it to display on separate lines, like so:
08701
Array
You might need to add a linebreak:
echo $_POST['zipcode'] . '<br/>';
If you wish to add breaks between print_r() statements:
print_r($latitude);
echo '<br/>';
print_r($longitude);
to break line with print_r:
echo "<pre>";
print_r($lookup->query($_POST['zipcode']));
echo "</pre>";
The element will format it with any pre-existing formatting, so \n will turn into a new line, returned lines (when you press return/enter) will also turn into new lines.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
If this is what your browser displays:
Array ( [locus] => MK611812 [version] => MK611812.1 [id] => 1588040742 )
And this is what you want:
Array
(
[locus] => MK611812
[version] => MK611812.1
[id] => 1588040742
)
the easy solution is to add the the <pre> format to your code that prints the array:
echo "<pre>";
print_r($final);
echo "</pre>";
Old question, but I generally include the following function with all of my PHP:
The problem occurs because line breaks are not normally shown in HTML output. The trick is to wrap the output inside a pre element:
function printr($data) {
echo sprintf('<pre>%s</pre>',print_r($data,true));
}
print_r(…, true) returns the output without (yet) displaying it. From here it is inserted into the string using the printf function.
Just echo these : echo $_POST['zipcode']."<br/>";
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®ion=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.