I want to convert PHP list (array), i.e.
array("start", "end", "coords")
into associative array with truthy values (just to be able to test the presence/absence of key quickly), i.e. to something like this:
array(
"start" => 1,
"end" => 1,
"coords" => 1
)
Is there any more elegant way to do it than this?
array_fill_keys($ar, 1)
There is probably no more elegant solution than array_fill_keys($ar, 1).
There is a function called array_flip that does this.
http://php.net/array_flip
Doing array_flip on an array and then using isset turned out to be much faster than doing in_array for me.
But note that this is only useful when you're going to be searching the array multiple times.
Related
I'm trying to find out if there's a way of removing an array element and at the same time storing that value in a variable.
i.e.
$array = [
'foo' => 'a',
'bar' => 'b'
];
// Perform the following with one action?
$var = $array['foo'];
unset($array['foo']);
Edit: I mean if it can be done without a custom function.
There is but it's slow and ugly.
$var = array_splice($array, array_search('foo', array_keys($array)), 1)['foo'];
I'd stick with the 2-liner.
It can be done under certain circumstances.
There are two functions which do what sort of what you want.
array_pop($stack);
array_shift($stack);
But array_pop gets and removes only the last element and array_push the first of the array which can lead to unexxpected behaviour of your code if you are using an associative array.
However if you can restructure your array to fit for these functions without increasing the complexity (which would make this whole thing pointless) it can be done.
The two links for the functions are:
array_pop
array_shift
An entire reference of the array function can be found here. Maybe you find something that serves you the way you need it to:
Array functions reference
Say, we make an array like this:
$arr = Array
(
2 => 'c',
1 => 'b',
0 => 'a'
);
When you pass it to array_pop():
array_pop($arr);
And the "last" element would be poped off, which has the index of zero!!
print_r($arr);
Result:
Array
(
[2] => c
[1] => b
)
So, what's the purpose of index?
Isn't it just a different way of saying "numeric keys of associative arrays"?
Is it only PHP dose so, or all the languages treat arrays like this?
Not all languages do this, but PHP does, because PHP is a little weird. It implements arrays more or less like dictionaries. PHP does offer some functions like ksort though, which let you sort the array by key.
And that's what this is: a key. An array has indexes as well, so what you got, is an array where item 2 has key 0. And that's where the confusion starts continues.
PHP: a fractal of bad design has a whole chapter about arrays. Interesting reading material. :)
The reason for this behavior is because arrays in PHP are actually unordered maps.
Because of this, don't think of accessing the arrays in terms of indexes, think of it in terms of keys. Keys can be numbers and they can be strings, but the result is the same; you're still using a map, not a true "array".
Once you accept that fact, you'll understand why PHP includes functions like ksort() for sorting an array by keys and why array_pop() doesn't always remove the highest key value.
It's a PHP thing. Other languages usually provide other structures to provide what is the default behaviour for arrays on PHP. JavaScript for instance will always sort the array:
a = [];
> []
a[1] = 'a';
> "a"
a[2] = 'b';
> "b"
a[0] = 'c';
> "c"
a
> ["c", "a", "b"]
In Java you would need to use a Hash Map or something else to do Associative Arrays. PHP handles data structures more loosely than other languages.
The index allows you to identify and access the elements of the array.
the reason is simple HashTables.
in php internal functions often use HashTables. basically an array is some data in memory and like in C - an array index can only hold integer values but not in php.
php solves this with hashtables. if you asign a index example foo this value is not directly assigned as foo it gets hashed and maybe end internal as 000000000111 and other hash functions.
so php doesn't work directly with your assigned value and this is the reason why you can set an array index like 0 as last index element. internal php work with hashtables that have a "list" with values which index value is assigned to which position in the array.
I have an array of unique colors which is selected from a table. But keys of that particular array is not in sequence order due to some calculations. Now I wish to assign a sequence numbers to that array... Is any function to change keys of array..
Thanks...
Array(
[81]=>yellow
[86]=>gray
[93]=>wine
[103]=>marigold
[125]=>maroon
[134]=>pewter
[142]=>forestgreen
[151]=>grey
)
i wish to change this array to
Array(
[1]=>yellow
[2]=>gray
[3]=>wine
[4]=>marigold
[5]=>maroon
[6]=>pewter
[7]=>forestgreen
[8]=>grey)
If you want to sort your array by some calculation, you can use usort(), which sorts an array by using a callback function. In this callback function, you can compare two elements of the array and decide (by any means you need) which one goes first. Read through the examples on the page I linked to learn more!
use: sort($color); check the examples from this link: sort
I am trying to modify an associative array eg.
array(
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3'
)
to something like
array(
':key1' => 'val1xx',
':key2' => 'val2xx',
':key3' => 'val3xx'
// ^ colen
)
You may recognize I am trying to convert it into something I can use in PDOStatement::execute(). I dont currently need to modify the value, in this case. But will like to know just for knowledge
What can I use to do that? I am thinking foreach can do most things, but do functions like array_map or array_walk provide any benefits? Like performance? Or just looks different
There exists a big performance gap between the foreach and the array_map method. The fastest is the foreach construct. This construct can be five to six times as fast as an anonymous function, at least when there is not much to do within the loop. In most scenarios, the time it takes to iterate over the array is negligible compared to the time spend in the loop or anonymous function. So this performance difference does not really matter.For more information see link here.
$result = array();
foreach ($array as $key => $value)
$result[":$key"] = "{$value}xx";
Thariama's answer points to the performance gap between the for loop and array_map. It should also be pointed that there is no loop-free manner for modifying the keys in an array. You can modify the values in different loop-free ways (including array_map and array_walk) but not the keys.
Is there any way to "custom" sort an array? For instance, if I have the following numbers:
$array = array('0' => 1, '1' => 2, '2' => 3);
I would like it to order them in this fashion:
$array = array('0' => 2, '1' => 1, '2' => 3);
How would I do this or is it not possible? I am basically wanting to list this array in one database field for each user, but each order will be different depending on how the user sorts the array.
Thanks, Jake
You can use
usort — Sort an array by values using a user-defined comparison function or
uksort — Sort an array by keys using a user-defined comparison function or
uasort — Sort an array with a user-defined comparison function and maintain index association
Each of these accepts an array and a user-defined comparison function aka callback. What you put into the comparion function is up to you. As of PHP5.3 you can also use SplHeaps to create ordered collections.
you may also want to have a look at array_multisort()
It might be better to let the database sort the array upon retrieval with the users settings. I think that is almost always preferable over sorting in PHP.
edit:
I forgot that the array is probably stored as a single object so the database just handles it as an object and not an array. To still enable serverside (database server) sorting, arrays could also be expressed as seperate tables:
userID : index0
userID : index1
etc...
but this might give too much data overhead.