I have an input:
$url = $params[0];
I have an array:
$dictionary = array(
"stock" => 1,
"user" => 2,
"zone" => 3);
How can I use the input to search the left values of this array (stock, user, zone, etc.) and get back the value on the right (1, 2, 3, etc.)?
Pretty simple, just access it like this
$dictionary[$url]
You can use this $url variable as a key to get the => value associated with it.
$dictionary = array(
"stock" => 1,
"user" => 2,
"zone" =>3);
$url = $params[0];
$yourDesiredValue = $dictionary[$url];
Since you are searching, you will want to check if the value (I presume $url) is set within the array and return it if true.
$value = false;
if (isset($dictionary[$url])) {
$value = $dictionary[$url];
}
Then, $value will be false if the search fails, but contain the number if the search is successful.
Related
I am aware that I could use a loop to answer my question, but I was hoping that maybe PHP has a function to do what I am trying to achieve and that someone might know.
Basically I am trying to identify a unique key from a series of arrays and then extract the value of the correlated key in the array.
So basically, from this array:
$myarray = array(array("id" => 1, "label" => "True"), array("id" => 2, "label" => "False"))
I want to be able to find the label value when the id is searched and matched, i.e. $id = 1 should return True.
Any simple functions available to do this without having to write a couple of loops?
It would be one simple loop. But if you are loopofobic, then you can rely on other functions (that acts as loop too):
function find(array $inputs, int $search): ?string
{
$result = array_filter($inputs, fn ($input) => $input['id'] === $search);
return current($result)['label'] ?? null;
}
$myarray = [["id" => 1, "label" => "True"], ["id" => 2, "label" => "False"]];
var_dump(find($myarray, 1)); // string(4) "True"
var_dump(find($myarray, 2)); // string(5) "False"
var_dump(find($myarray, 3)); // NULL
Live Example
you may use the built-in function array_column() for your aim.
$myarray = array(array("id" => 1, "label" => "True"), array("id" => 2, "label" => "False"));
/* label (value) per id (key) in 1-dimensional array.*/
print_r(array_column($myarray,'label','id'));
will return
Array
(
[1] => True
[2] => False
)
so you may adjust the code below.
$myarray = array(array("id" => 1, "label" => "True"), array("id" => 2, "label" => "False"));
$id_val = 1;
$output = isset(array_column($myarray,'label','id')[$id_val]) ? array_column($myarray,'label','id')[$id_val] : 'key not found';
var_dump($output);
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.
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.
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.
I have an array with default settings, and one array with user-specified settings. I want to merge these two arrays so that the default settings gets overwritten with the user-specified ones.
I have tried to use array_merge, which does the overwriting like I want, but it also adds new settings if the user has specified settings that doesn't exist in the default ones. Is there a better function I can use for this than array_merge? Or is there a function I can use to filter the user-specified array so that it only contains keys that also exist in the default settings array?
Example of what I want
$default = array('a' => 1, 'b' => 2);
$user = array('b' => 3, 'c' => 4);
// Somehow merge $user into $default so we end up with this:
Array
(
[a] => 1
[b] => 3
)
You can actually just add two arrays together ($user+$default) instead of using array_merge.
If you want to stop any user settings that don't exist in the defaults you can use array_intersect_key:
Returns an associative array containing all the entries of array1 which have keys that are present in all arguments
Example:
$default = array('a' => 1, 'b' => 2);
$user = array('b' => 3, 'c' => 4);
// add any settings from $default to $user, then select only the keys in both arrays
$settings = array_intersect_key($user + $default, $default);
print_r($settings);
Results:
Array
(
[b] => 3
[a] => 1
)
The keys/values (and order) are selected first from $user in the addition, which is why b comes before a in the array, there is no a in $user. Any keys not defined in $user that are defined in $default will then be added to the end of $user. Then you remove any keys in $user + $default that aren't defined in $default.
It's probably simplest to just loop over the keys in the default-settings array, if you only want to consider those. So you can do something like this:
foreach ($default_settings AS $key => $default_value)
{
if (array_key_exists($key, $user_settings))
{
$combined_settings[$key] = $user_settings[$key];
}
else
{
$combined_settings[$key] = $default_value;
}
}
foreach($default as $key=>$val){
if (isset($user[$key]))
{
$settings[$key] = $user[$key];
} else {
$settings[$key] = $default[$key];
}
}
I think this is what you want.
foreach($user_settings as $key=>$val){
$global_settings[$key] = $val;
}
?