PHP adressing the first key in an array that changes - php

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..

Related

Php access variable

In PHP i have array variable from another function like this
$v->params:
(
[{"username":"myusername","email":"myemail#gmail_com","phone":"0123456789","password":"abc123","fullname":"myfullname","register_ip":"127_0_0_1","country":"Qu\u1ed1c_Gia","birthday":"N\u0103m_sinh","gender":"male","bank_code":"Ng\u00e2n_h\u00e0ng","ip":"127_0_0_1","os":"Windows_10","device":"Computer","browser":"Mozilla_Firefox_77_0"}] =>
)
Now i want to access to it item, how can i code to access item value like this:
$password = $v->params->password; //myemail#gmail_com
I new with PHP thank you all
The data seems the wrong way round as it's the key of the array rather than a value.
So using array_keys()[0] to get the first key and then json_decode this...
$data = json_decode(array_keys($v->params)[0]);
you can then use the $data object to get at the values...
echo $data->username;

array_dif not working as the output is empty

I created 2 arrays and want to check for the difference between both arrays (values). If I use my arrays with the function array_diff, the response is a empty Array, which is very wierd as I can't find the problem at all.
My setup:
// first array
$listing_products_sku = [
'55995', '55996', '55999', '56000', '56005', '56006', '56007',
'56008', '56021', '56022', '56023', '56024', '56029', '56030',
'56031', '56032', '56036', '56037',
];
// second array:
$internal_products_sku = [
'56015', '56016', '56014', '56018', '56019', '56020', '55994',
'55995', '55996', '55997', '55998', '55999', '56000', '56001',
'56002', '56003', '56005', '56004', '56006', '56007', '56008',
'56009', '56010', '56011', '56012', '56013', '56017', '56021',
'56022', '56023', '56024', '56025', '56026', '56027', '56028',
'56029', '56030', '56031', '56032', '56033', '56034', '56035',
'56036', '56037', '56038', '56039', '56040', '56041', '60434',
'60435',
];
// used function:
$diff_result = array_diff($listing_products_sku, $internal_products_sku);
print_r($diff_result);
Output
Array ( )
Help needed
Is anybody able to explain why this happens and how I can make this working?
array_diff() returns array from first array containing values not exist in rest of the arrays (http://php.net/manual/en/function.array-diff.php). As your first array's element are already exist in second array ($internal_products_sku) this is why its returning empty array.
So to find the difference all you have to do is take the $internal_products_sku array as first param then check
$diff_result = array_diff($internal_products_sku, $listing_products_sku);
print_r($diff_result);
Now it will return an array with those value not exist in $listing_products_sku

PHP JSON Arrays within an Array

I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);

Php array_rand() printing variable name

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

php: get array value without iterating through it?

hey guys,
i think i lost my mind.
print_r($location); lists some geodata.
array (
'geoplugin_city' => 'My City',
'geoplugin_region' => 'My Region',
'geoplugin_areaCode' => '0',
'geoplugin_dmaCode' => '0',
'geoplugin_countryCode' => 'XY',
'geopl ...
when I iterate through it with a foreach loop I can print each line.
However shouldn't it be possible to just get a specific value out of the array?
like print $location[g4]; should print the countryCode shouldn't it? Thank you!
echo $location['geoplugin_countryCode'];
Yes, you can get a specific value by key. The keys in your case are the geoplugin_ strings.
To get the country code:
// XY
$location['geoplugin_countryCode'];
$location['geoplugin_countryCode'];
would access country code
Where does "g4" come from? Did you mean "4"?
If you had a normal numerically-indexed array then, yes, you could write $location[4]. However, you have an associative array, so write $location['geoplugin_countryCode'].
there you are using an associative array, it is an array with a user defined key:value pair (similar to dictionaries on Python and Hash Tables on C#)
You can access the elements just using the Key (in this case geoplugin_city or geoplugin_region)
Using the standard array syntax:
$arrayValue = $array[key]; //read
$array[key] = $newArrayValue; //write
For example:
$location['geoplugin_city']; or $location['geoplugin_region'];
If you are not familiarwith PHP arrays you can take a look here:
http://php.net/manual/en/language.types.array.php
For a better understanding on array manipulation with PHP take a look of:
http://www.php.net/manual/en/ref.array.php

Categories