How to Get The Value Which is being set with GET? - php

I'm using GET to obtain information (unsensitive, of course) and in a URL such as this: http://www.sample.com/foo.php?KEY=VALUE if I wanted to obtain the text "KEY" from that, is it possible?

Try this
foreach($_GET as $key => $value) {
echo $key; // will print 'KEY'
echo $value; // will print 'VALUE'
}

Search Array for Value, Return Key
You could use array_search, which functions similar to using array_keys with the second argument:
$array = array( "Name" => "Jonathan" );
$key = array_search( "Jonathan", $array );
echo $key; // Name
Note that when searching for strings in this manner, your search will be case-sensitive, so make sure you get the case correct. This will return the first key found that corresponds to your search value. If many keys are found, only the first will be returned.
Retrieve Array Keys in Array
If you want all of your keys, you can use array_keys. This returns an array of keys. From this, you could find the one you want, and then use it to grab the corresponding value from $_GET.
$array = array( "Name" => "Jonathan", "Site" => "StackOverflow" );
$aKeys = array_keys( $array );
print_r( $aKeys );
Which results in the following array:
Array
(
[0] => Name
[1] => Site
)
Retrieve Array of Keys for Search
You can provide an optional second value for this function as well, which is the value for which you would like to get the corresponding key. In the array above (and the same goes for $_GET) I can get the key used for "Jonathan" by searching for "Jonathan":
$array = array( "Name" => "Jonathan", "Site" => "StackOverflow" );
$aKeys = array_keys( $array, "Jonathan" );
print_r( $aKeys );
This results in the following array:
Array
(
[0] => Name
)

Related

php setting value in multi dimensinal array depending on array of indices

When gathering statistical data I need to address an array with a varying number of indices.
I have to add to $array[$ind1][$ind2] and to $array[$ind1][$ind2][$ind3][$ind4].
Is it possible to create a function like arrayAdd($number,$arrayOfIndices)
where in the first case $arrayOfIndices is [$ind,$ind2]
and the second case [$ind1,$ind2,$ind3,$ind4]?
I solved my problem to write it all out, depending of count of $arrayOfIndices.
Looking however to a more elegant and generic way.
<?php
function array_add(&$array, array $indices, $value) {
count($indices)==1
? $array[$indices[0]] = $value
: array_add($array[array_shift($indices)], $indices, $value);
}
$data = ['pig'=>'man'];
$indices = ['foo', 'bar', 'baz'];
array_add($data, $indices, 'bat');
var_export($data);
Output:
array (
'pig' => 'man',
'foo' =>
array (
'bar' =>
array (
'baz' => 'bat',
),
),
)

Working with multidimensional array with PHP

I have this array:
$datas = array(
array(
'id' => '1',
'country' => 'Canada',
'cities' => array(
array(
'city' => 'Montreal',
'lang' => 'french'
),
array(
'city' => 'Ottawa',
'lang' => 'english'
)
)
)
);
Question 1:
How can I get the the country name when I have the id ?
I tried: $datas['id'][1] => 'country'
Question 2:
How can I loop in the cities when I have the id ?
I tried:
foreach ($datas as $data => $info) {
foreach ($info['cities'] as $item) {
echo '<li>'.$item['city'].'</li>';
}
}
Thanks a lot.
You have the ID of the array you want analyse, but your array is structured as a map, meaning that there are no keys in the outer array. You will therefore have to iterate the array first to find the object you are looking for.
While the first approach would be to search for the object that has the ID you are looking for, i suggest you map your arrays with their IDs. To do that, you can use two PHP array functions: array_column and array_combine.
array_column can extract a specific field of each element in an array. Since you have multiple country objects, we want to extract the ID from it to later use it as a key.
array_combine takes two arrays with the same size to create a new associative array. The values of the first array will then be used as keys, while the ones of the second array will be used as values.
$mappedCountries = array_combine(array_column($datas, 'id'), $datas);
Assuming that the key 1 is stored in the variable $key = 1;, you can afterwards use $mappedCountries[$key]['country'] to get the name of the country and $mappedCountries[$key]['cities'] to get the cities, over which you can then iterate.
if there might be many arrays in $datas and you want to find one by id (or some other key) you can do something like this:
function search($datas, $key, $value) {
foreach($datas as $data) {
if ($data[$key] === $value) {
return $data;
}
}
So if you want to find where id = 1
$result = search($datas, 'id', '1');
and then you can get country echo $result['country'] or whatever you need.

php extract sub array with specific key

if i have the following array:
array(
'var1' => 123,
'var2' => 234,
'var3' => 345
);
I would like to extract specific parts of this to build a new array i.e. var1 and var3.
The result i would be looking for is:
array(
'var1' => 123,
'var3' => 345
);
The example posted is very stripped down, in reality the array has a much larger number of keys and I am looking to extract a larger number of key and also some keys may or may not be present.
Is there a built in php function to do this?
Edit:
The keys to be extracted will be hardcoded as an array in the class i..e $this->keysToExtract
$result = array_intersect_key($yourarray,array_flip(array('var1','var3')));
So, with your edit:
$result = array_intersect_key($yourarray,array_flip($this->keysToExtract));
You don't need a built in function to do this, try this :
$this->keysToExtract = array('var1', 'var3'); // The keys you wish to transfer to the new array
// For each record in your initial array
foreach ($firstArray as $key => $value)
{
// If the key (ex : 'var1') is part of the desired keys
if (in_array($key, $this->keysToExtract)
{
$finalArray[$key] = $value; // Add to the new array
}
}
var_dump($finalArray);
Note that this is most likely the most efficient way to do this.

PHP take array key and value from beginning and put at end

I have a PHP array that has literal_key => value. I need to shift the key and value off the beginning of the array and stick it at the end (keeping the key also).
I've tried:
$f = array_shift($fields);
array_push($fields, $f);
but this loses the key value.
Ex:
$fields = array ("hey" => "there", "how are" => "you");
// run above
this yields:
$fields = array ("how are" => "you", "0" => "there");
(I need to keep "hey" and not have 0) any ideas?
As far as I can tell, you can't add an associative value to an array with array_push(), nor get the key with array_shift(). (same goes for pop/push). A quick hack could be:
$fields = array( "key0" => "value0", "key1" => "value1");
//Get the first key
reset($fields);
$first_key = key($fields);
$first_value = $fields[$first_key];
unset($fields[$first_key]);
$fields[$first_key] = $first_value;
See it work here. Some source code taken from https://stackoverflow.com/a/1028677/1216976
You could just take the 0th key $key using array_keys, then set $value using array_shift, then set $fields[$key] = $value.
Or you could do something fancy like
array_merge( array_slice($fields, 1, NULL, true),
array_slice($fields, 0, 1, true) );
which is untested but has the right idea.

Best way to refer index which contains in array

In php I'm willing to check the existence of indexes that match with another values in array.
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
MY ideal result is, in this case, to get "form" and "date". Any idea?
Try
$fields_keys = array_keys($fields);
$fields_unique = array_diff($fields_keys, $indexes);
The result will be an array of all keys in $fields that are not in $indexes.
You can try this.
<?php
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
$b = array_diff(array_keys($fields), $indexes);
print_r($b);
You can use array_keys function to retrieve keys of a array
Eg:
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
Outputs
Array
(
[0] => 0
[1] => color
)
PHP Documentation
Your question is a little unclear but I think this is what you're going for
array_keys(array_diff_key($fields, array_fill_keys($indexes, null)));
#=> Array( 0=>"form", 1=>"date" )
See it work here on tehplayground.com
array_keys(A) returns the keys of array A as a numerically-indexed array.
array_fill_keys(A, value) populates a new array using array A as keys and sets each key to value
array_diff_key(A,B) returns an array of keys from array A that do not exist in array B.
Edit turns on my answer got more complicated as I understood the original question more. There are better answers on this page, but I still think this is an interesting solution.
There is probably a slicker way than this but it will get you started:
foreach(array_keys($fields) as $field) {
if(!in_array($field, $indexes)) {
$missing[] = $field;
}
}
Now you will have an array that holds form and date.

Categories