php key value array get value
get value by key of php object array
I have a PHP object and I am trying to get the value by the key without using a foreach.
If I do the below I am able to get the value:
but the items may be in different orders so cannot count on this method and I need to use the key however this doesn’t work:
Adding true to the json_decode provides the following:
3 Answers 3
Personally I would prepare the data like this:
The second param in json_decode makes sure it returns only arrays (Manual.). This way you can use array function like array_column (Manual) and array_combine (Manual), and get an array that is very close to the structure you want.
Test Case, since no code is to short for it.
Accessing each property is how you normally access a property of an object.
Note that since «First name» has a space, it cannot be accessed by the arrow notation and must be enclosed in curly braces. For any property that doesn’t have a space, there is no need for the curly braces.
The reason your code was failing is because you were trying to access properties using the square bracket notation used for arrays.
I am aware that you are not able to edit the actual array output, but if you can edit the JSON then this will solve your problems.
If you can modify the array structure, then structure it like this:
You can then still use this array in a foreach loop as before if needed, albeit with some changes, while being able to access the value you want directly.
If you can’t modify the array structure, then you’re out of luck and a foreach loop is required if you want to find the value you want.
If your concern is performance of accessing the array multiple times, then consider transforming the array to the structure above before processing.
array_keys
(PHP 4, PHP 5, PHP 7, PHP 8)
array_keys — Возвращает все или некоторое подмножество ключей массива
Описание
Список параметров
Массив, содержащий возвращаемые ключи.
Если указано, будут возвращены только ключи у которых значения элементов массива совпадают с этим параметром.
Определяет использование строгой проверки на равенство (===) при поиске.
Возвращаемые значения
Примеры
Пример #1 Пример использования array_keys()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 28 notes
It’s worth noting that if you have keys that are long integer, such as ‘329462291595’, they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.
?>
will return on a 64 bits system:
but on a 32 bits system:
I hope it will save someone the huge headache I had 🙂
Here’s how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:
Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.
Invalid:
echo array_shift( array_keys( array(‘a’ => ‘apple’) ) );
But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:
echo array_shift( ( array_keys( array(‘a’ => ‘apple’) ) ) );
However I would expect in time the PHP team will modify the rules of parentheses.
There’s a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.
Here’s a way to find all the keys from a multidimensional array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.
NOTE: If the sub element isn’t an array, it will be ignore.
output:
array(
‘Player’ => array(),
‘LevelSimulation’ => array(
‘Level’ => array(
‘City’ => array()
)
),
‘User’ => array()
)
array (size=4)
0 => string ‘e’ (length=1)
1 => int 1
2 => int 2
3 => int 0
—-
expected to see:
dude dude dude
Sorry for my english.
I wrote a function to get keys of arrays recursivelly.
Here’s a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.
?>
Example usage (pseudo-database code):
= db_query ( ‘SELECT name, value FROM properties’ );
/* This will return an array like so:
/* Now this array looks like:
?>
I found this handy for using with json_encode and am using it for my project http://squidby.com
This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don?t have control of depths.
An alternative to RQuadling at GMail dot com’s array_remove() function:
The position of an element.
One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output «yes, we have bananas at position 0».
Hope this helps someone.
# array_keys() also return the key if it’s boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array:
Array
(
[ 0 ] => first_index
[ 1 ] => 1
[ 2 ] => 0
[ 3 ] => 4
[ 4 ] => 08
[ 5 ] => 8
[ 6 ] =>
)
This function will extract keys from a multidimensional array
Array
(
[color] => Array
(
[1stcolor] => blue
[2ndcolor] => red
[3rdcolor] => green
)
[size] => Array
(
[0] => small
[1] => medium
[2] => large
)
Array
(
[0] => color
[1] => 1stcolor
[2] => 2ndcolor
[3] => 3rdcolor
[4] => size
[5] => 0
[6] => 1
[7] => 2
)
All the cool notes are gone from the site.
Here’s an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.
Simple ways to prefixing arrays;
[1] => Array
(
[product_id] => 2
[product_name] => Bar
)
I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn’t find a function I came up with my own solution.
I didn’t find the propiest function to post to so I will post it here, hope you find it useful.
?>
You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string
A needed a function to find the keys which contain part of a string, not equalling a string.
How to get array key from corresponding array value?
5 Answers 5
You could use array_search() to find the first matching key.
You can use the array_keys function for that.
Example:
This will get the key from the array for value blue
If you do this often, create a reverse array/hash that maps values back to keys. Keep in mind multiple keys may map to a single value.
Your array values can be duplicates so it wont give you exact keys. However the way i think is fine is like iterate over and read the keys
Not the answer you’re looking for? Browse other questions tagged php arrays or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Is there a better PHP way for getting default value by key from array (dictionary)?
In Python one can do:
In PHP one can go for a trinary operator as in:
I am looking for a golf version. Can I do it shorter/better in PHP?
UPDATE [March 2020]:
found in the comments below (+1)
8 Answers 8
I just came up with this little helper function:
Not only does this work for dictionaries, but for all kind of variables:
Use the error control operator @ with the PHP 5.3 shortcut version of the ternary operator:
I find it useful to create a function like so:
And use it like this:
I hope it is useful.
PHP 5.3 has a shortcut version of the ternary operator:
which is basically
Otherwise, no, there’s no shorter method.
A «slightly» hacky way to do it:
Obviously this isn’t really the nice way to do it. But it is handy in other situations. E.g. I often declare shortcuts to GET and POST variables like that:
PS: One could call this the «built-in ==$_=& special comparison operator»:
PPS: Well, you could obviously just use
but that’s even worse than the ==$_=& operator. People don’t like the error suppression operator much, you know.
If you enumerate the default values by key in an array, it can be done this way:
The more key/value pairs that you enumerate defaults for, the better the code-golf becomes.
But it doesn’t use isset inside and produces notices. To avoid notices better to use Null Coalescing Operator ?? which uses isset inside it. Available in PHP 7.
Example #5 Assigning a default value
array_values
(PHP 4, PHP 5, PHP 7, PHP 8)
array_values — Выбирает все значения массива
Описание
Список параметров
Возвращаемые значения
Возвращает индексированный массив значений.
Примеры
Пример #1 Пример использования array_values()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 25 notes
Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the ‘foreach’ ordering:
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.
Doing this will cause PHP exceeds the momory limits:
Most of the array_flatten functions don’t allow preservation of keys. Mine allows preserve, don’t preserve, and preserve only strings (default).
echo ‘var_dump($array);’.»\n»;
var_dump($array);
echo ‘var_dump(array_flatten($array, 0));’.»\n»;
var_dump(array_flatten($array, 0));
echo ‘var_dump(array_flatten($array, 1));’.»\n»;
var_dump(array_flatten($array, 1));
echo ‘var_dump(array_flatten($array, 2));’.»\n»;
var_dump(array_flatten($array, 2));
?>
If you are looking for a way to count the total number of times a specific value appears in array, use this function:
I needed a function that recursively went into each level of the array to order (only the indexed) arrays. and NOT flatten the whole thing.
Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:
/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)
array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
same array_flatten function, compressed and preserving keys.
/**********************************************
*
* PURPOSE: Flatten a deep multidimensional array into a list of its
* scalar values
*
* array array_values_recursive (array array)
*
* WARNING: Array keys will be lost
*
*********************************************/
Non-recursive simplest array_flatten.
A modification of wellandpower at hotmail.com’s function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.
Please note that ‘wellandpower at hotmail.com’s recursive merge doesn’t work. Here’s the fixed version:
The function here flatterns an entire array and was not the behaviour I expected from a function of this name.
I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.
In order to do this, you will want this function:
function array_values_recursive($array) <
$temp = array();
Hopefully this will assist.
Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus «preserving keys» may have different interpretations. Ivan’s function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.
/*
* Flattening a multi-dimensional array into a
* single-dimensional one. The resulting keys are a
* string-separated list of the original keys:
*
* a[x][y][z] becomes a[implode(sep, array(x,y,z))]
*/