Php array_rand() printing variable name - php

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)];

Related

$$array[0] returns array name letter and not array value

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.

PHP adressing the first key in an array that changes

For example, lets say I have an array that looks liked
$stuff = array('random_string_1' => 'random_value_1','random_string_2' => 'random_value_2');
and then I call the asort() function and it changes the array around. How do I get the new first string without knowing what it actually is?
If you want to get the first value of the array you can use reset
reset($stuff);
If you want to also get the key use key
key($stuff);
If you need to get the first value, do it like this:
$stuff = array('random_string_1' => 'random_value_1','random_string_2' => 'random_value_2');
$values = array_values($stuff); // this is a consequential array with values in the order of the original array
var_dump($values[0]); // get first value..
var_dump($values[1]); // get second value..

PHP get key value from array

When I put print_r($data); I get the following
Array
(
[name] => Cheese
)
Is there a way to get the key name in a variable on its own?
There may be occasions that name could be email and other values.
Use array_keys():
var_dump(array_keys($data));
Return all the keys or a subset of the keys of an array
Do you mean you know the value but you don't know the key? If so you could write something like this:
$array = ['name' => 'Cheese'];
array_flip($array);
var_export($array['Cheese']); // Output: name
You can have the array key extracted to their own variables using the extract function. For example
$a = array("color"=>"blue");
extract($a);
echo $color;

Serialised Array not working

I am trying to take an array of filenames and output the following...
a:1:{s:4:"docs";a:4:{i:0;a:1:{s:15:"property_imgurl";s:63:"http://wwww.example.com/image1.jpg";}i:1;a:1:{s:15:"property_imgurl";s:63:"http://wwww.example.com/image2.jpg";}i:2;a:1:{s:15:"property_imgurl";s:63:"http://wwww.example.com/image3.jpg";}i:3;a:1:{s:15:"property_imgurl";s:63:"http://wwww.example.com/image4.jpg";}}}
This is what I have so far...
<?php
$serialized_data = serialize(array('http://www.example.com/image1.jpg', 'http://www.example.com/image2.jpg', 'http://www.example.com/image3.jpg', 'http://www.example.com/image4.jpg'));
echo $serialized_data . '<br>';
?>
But this is giving me...
a:4:{i:0;s:34:"http://www.example.com/image1.jpg";i:1;s:34:"http://www.example.com/image2.jpg";i:2;s:34:"http://www.example.com/image3.jpg";i:3;s:34:"http://www.example.com/image4.jpg";}
Where am I going wrong?
There is nothing wrong with the serialized array. You're just not creating the array like you want it to be. PHP can't guess how you really want your array to be, so you have to tell PHP how you want it to be. So what you need to do is to change the input array correctly.
You're giving
array('http://www.example.com/image1.jpg', 'http://www.example.com/image2.jpg', 'http://www.example.com/image3.jpg', 'http://www.example.com/image4.jpg')
and that's completely different from the serialized array how it should be. Your Array needs to look like this
array('docs' => array(array('property_imgurl' => 'http://www.example.com/image1.jpg'), array('property_imgurl' => 'http://www.example.com/image2.jpg'), array('property_imgurl' => 'http://www.example.com/image3.jpg'), array('property_imgurl' => 'http://www.example.com/image4.jpg')))
Look at this eval
You're just missing the array key definitions.
$serialized = array(array('docs' => array(array('property_imgurl' => 'http://www.example.com/image4.jpg'))));
As you can see, each URL has a key of property_imgurl and each of those array is part of a parent array with a key of docs
Here's the eval.in

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