Using numbers as assoc array keys - php

It seems to work, but it feels wrong, I assume it is.
Is it wrong?
If so, I currently have an array with keys being mysql database id's and the values being their values.
Would it be better to have the key being "record_"+$id and then explode()ing the key and getting the id from that?
Or is it ok to set your own array keys, and php will just assume they are assoc array keys, rather than indexes?
Thanks

Some built-in PHP functions (like array_merge / array_multisort) will re-index your array:
array_merge() If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If,
however, the arrays contain numeric keys, the later value will not
overwrite the original value, but will be appended. Values in the
input array with numeric keys will be renumbered with incrementing
keys starting from zero in the result array.
array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative
(string) keys will be maintained, but numeric keys will be re-indexed.
I would advise you not to do that, use a proper value instead, or at the very least prefix it with a short _:
foreach ($array as $key => $value)
{
$id = ltrim($key, '_');
// do stuff with the actual $id
}

Related

How do you find most common array in multidimensional array using PHP

I need to find the most common (most occurring) array in a multidimensional array. Not the most common values like this post - Find Common most values in multidimensional array in PHP - but rather the most common combination.
For example, if I have the following:
$a1=array(
array('704322062'),
array('678073776', '704322062'),
array('678073776', '704322062'),
array('704322064'),
array('704322062'),
array('678073776'),
array('678073776', '704322062')
);
I want to be able to detect that the array that occurs most often is array('678073776', '704322062') not that the string '704322062' is most common.
I've tried using array_intersect but couldn't get it working for this scenario.
Thanks!
array_count_values only works with scalar values, not when the items are arrays themselves. But we can still use that function, if we transform your arrays into strings first - by encoding them as JSON.
// fill temp array with items encoded as JSON
$temp = [];
foreach($a1 as $item) {
$temp[] = json_encode($item);
}
// count how many times each of those values occurs
$value_counts = array_count_values($temp);
// sort by number of occurrence, while preserving the keys
ksort($value_counts);
// pick the first key from the temp array
$first = array_key_first($value_counts);
This will get you ["678073776","704322062"] in $first now - you can json_decode it again, if you want your “original” array.
Note that this does not take into account, that two arrays could occur the same amount of times - then it will just pick the “random” first one of those. If you need to handle that case as well somehow, then you can determine the maximum value in $temp first, and then filter it by that value, so that only those keys of the corresponding arrays will be left.

Need to merge arrays but leave only one value if duplicated

I have two arrays with the same keys but different values. I need to merge it but if the values are the same leave only one of this
$array1 = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_1);
$array2 = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_2);
I need to get:
$array_result = array('firstname'=> $may_name, 'lastname'=>$my_last_name, 'address'=>$addres_1, 'address'=>$addres_2);
can anybody help to solve this?
array_merge does not work for me..
First you need to merge 2 arrays, using array_merge() function. then get the unique elements from the array using array_unique() function will get you the result
var_dump(array_unique(array_merge($array1, $array2)));
Edit
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
php doc
Thanks #Marco

How does mysql_fetch_array($result_type=MYSQL_BOTH) return both associative and numeric indices?

In the documentation http://php.net/manual/en/function.mysql-fetch-array.php, it states that "By using MYSQL_BOTH (default), you'll get an array with both associative and number indices." But it is my understanding that php arrays can either be associative or numeric, not both. You could obviously create an associative array that contains the numeric indices as well, as keys, but that would double the array count. So how do they do this? Have they made a special exception for this one function? Is what it returns not actually a conventional array but their own special array just for this purpose? Or is there something that I am missing?
According to the PHP Documentation on Arrays a PHP array is "Actually an ordered map", and can be both associative and numeric. Using MYSQL_BOTH uses associative and numeric keys in the same array.

Are numeric and associative arrays in PHP two different things?

This is a deeper dive into a previous question I had here: Can items in PHP associative arrays not be accessed numerically (i.e. by index)?
According to W3Schools, :
In PHP, there are three kind of
arrays:
Numeric array - An array with a numeric index
Associative array - An array where each ID key is associated with a value
Multidimensional array - An array containing one or more arrays
But is this accurate? Each element in the array can be assigned either an index or a string as a key- so what happens when the two are mixed in the same array?
$myArray[0] = 'value1';
$myArray['one'] = 'value2';
All arrays in PHP are the same; they're implemented as hash maps which associate keys to values, whatever type the keys may be.
Manual:
The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.
If an array had both numeric and non-numeric indices, though, I'd still call it an associative array. The meaning of "associative" still stands.
Wikipedia:
An associative array is an abstract data type composed of a collection of unique keys and a collection of values, where each key is associated with one value (or set of values).
...
From the perspective of a computer programmer, an associative array can be viewed as a generalization of an array. While a regular array maps an integer key (index) to a value of arbitrary data type, an associative array's keys can also be arbitrarily typed. In some programming languages, such as Python, the keys of an associative array do not even need to be of the same type.
For the last sentence, the same applies for PHP, as shown in your example.
PHP doesn't really have arrays. They are dictionaries. Numeric keys are allowed at the same time as string keys. They can be mixed and do coexist.
(Actually string keys like "123" are always treated as integers. PHP does not keep the type information for them.)
If you want a different behaviour you could implement and extend ArrayObject however. And it would be possible to implement a map, where numeric keys functioned as alias to string indexes.
In general, you should read the official documentation rather than W3Schools.
An array can contain whatever members it wants with whatever keys it wants.
The description provided by W3Schools is quite ambiguous, or even wrong.
Numeric array - An array with a numeric index
I'd say a numeric array is an array with only integer indexes. An array with one I'd probably call a mixed (or associative, see below) array, if I had to call it anything.
Associative array - An array where each ID key is associated with a value.
I don't know about that description. I'd say an array can be associative if it maps strings to values instead of numerical indexes.
Multidimensional array - An array containing one or more arraysNumeric array - An array with a numeric index
An associative array can contain arrays too, which makes it multidimensional.
Keep in mind that an array with all numeric keys (even if in a string) will always be treated as a numeric array. This can mean different things in different contexts.
$arr = array(
'1' => 'abc',
2 => 'def'
);
var_dump($arr);
Output
array(2) {
[1]=>
string(3) "abc"
[2]=>
string(3) "def"
}
You get an associative array. Try this code:
$myArray[0] = 'value1';
$myArray['one'] = 'value2';
echo($myArray[1]);
See? It doesn't echo anything.
Something inportant to note about a PHP well ordered numerical array versus a un-ordered numerical PHP array where the order is not respected (3, 1, 2, 0 instead of 0, 1, 2, 3 ...) is when you are working with an API returning JSON payloads. On the client side, e.g a client written in Javascript, and if you're expecting an array and not an object you could have some difficulties. That's why sometime, on the PHP side, you can see something as follows being returned :
return array_values($array);

add values from arrays to an array?

how do i add values from arrays to an array so that it grows by time.
eg.
all values form array1 to myArray.
all values form array2 to myArray.
so now myArray contains all values from 1 and 2.
i want to do this in a cpu efficient way
$myArray = array_merge($array1, $array2);
See the documentation, as there are a few things you will want to know about how duplicates and numerical keys are handled.
Either use the array_merge() function (also see array_merge_recursive()):
$myArray = array_merge($array1, $array2);
If the input arrays have the same
string keys, then the later value for
that key will overwrite the previous
one. If, however, the arrays contain
numeric keys, the later value will not
overwrite the original value, but will
be appended.
Or use the Union Array Operator (+):
$myArray = $array1 + $array2;
The + operator appends elements of
remaining keys from the right handed
array to the left handed, whereas
duplicated keys are NOT overwritten.

Categories