check if two different values exists in a php array - php

Let's say I have a php array that could be all 1s, all 2s or all 1s and 2s. For example I could have array(1, 1, 1, 1, 1, 1), or array(2, 2, 2, 2, 2, 2) or array(2, 2, 1, 1, 2, 1).
How do I check if my array actually is an array of all 1s, all 2s or if my array actually contains both 1s and 2s?

In case you wanted to know for PHP, you can use array_unique() to probe which distinct values exist:
if (count(array_unique($array)) == 1) {
// It's either full of 1s or 0s.
// Then just probe the first entry.
}

You could add all the values in the array together. If they equal the length of the array or they equal 0 they are all 1s or all 0s.

The simplest way is to just count the number of ones and zeroes. For example (in python):
ones = zeroes = 0;
for i in range(len(my_array)):
if my_array[i] == 1: ones = ones + 1
else zeroes = zeroes + 1
You can also multiply each element together (1 if all ones) and add each element in the array (0 if all elements are zero)

In Java ...
public static void allTheSame(int[] array) {
for (int i = 1; i < array.length; i++) {
if (array[i] != array[i - 1]) {
return false;
}
}
return true;
}
This algorithm can be transcribed into the other listed languages, though their may be neater ways to do it in some. (But watch out for the efficiency of the neat solutions ... if that matters to your application.)
Note that this approach will deliver a false result faster than any neat solution that involves collating or summing the array elements, and it makes no assumption about what the element values are.
Note: this answer was written when the tagging indicated that the OP wanted solutions in Java, Javascript and PHP. Check the Question's edit history ...

You can do it with a simple if-statement. Here's some JavaScript:
if (myArray.indexOf(1) > -1) {
// there are 1s, are there 0s?
if (myArray.indexOf(0) > -1) {
console.log("1s and 0!");
} else {
console.log("Only 1s.");
}
} else {
console.log("Only 0s.");
}
Working example: http://jsfiddle.net/daNEH/

Try this code:
int[] intArray = new int[5];
boolean hasZero, hasOne, hasBoth;
for(int integer : intArray)
{
switch(integer)
{
case 0:
hasZero = true;
break;
case 1:
hasOne = true;
break;
}
}
hasBoth = hasZero && hasOne;

function allElementsEqual(array){
var start = array[0],
same = true;
for(i = 1;i < array.length;i++){
same &= (start === array[1]);
}
return same;
}
This function should do the job fine http://jsfiddle.net/WNxg4/

Another way would be to use array_diff, provided you only had two different numbers. Just compare the haystack of numbers to an array with a single number (pick one of the ones in the haystacks).
For example:
$haystack_mixed = array(2,2,2,1,1);
$haystack_1 = array(1,1,1,1);
$haystack_2 = array(2,2,2,2);
print_r(array_diff($haystack_mixed, array(1)));
// The result is not the same as the $haystack since there are 1's in it.
// Array ( [0] => 2 [1] => 2 [2] => 2 )
print_r(array_diff($haystack_1, array(1)));
// This one is made up of all 1's
// Array ( )
print_r(array_diff($haystack_2, array(1)));
// This one is made up of all 2's (same length as $haystack_2)
// Array ( [0] => 2 [1] => 2 [2] => 2 [3] => 2 )
So you can test the length of the resulting array.

I think you could use the array_sum or array_filter functions for this.

I have read the 9 answers and they're all pretty fancy, I think just go with the simplest way.
is_mixed($array){
$count = count($array);
//we go trough every element in the array
for($i=1;$i<$count;$i++){
//if the element n is distinct from the n-1
//then return true (is_mixed)
if ($array[$i] != $array[$i-1]) return true;
}
//if it didn't return anything yet, it means
//all the elements are the same. Then, just
//return the first one, as they're all the same
// (either 1 or 2)
return $array[0];
}
this second one I actually like the most:
function what_they_are($array){
$total = array_sum($array);
$count = count($array);
if ($total == 0) {
return "they're all 0";
}else if ($total/$count == 2){
return "they're all 2";
}else if ($total == $count){
return "they're all 1";
}else{
return "they're mixed";
}
}

Related

PHP array intersect for only one occurrence of value

I'm trying to create a function to find the HCF of two values. I currently have a function that finds all the prime factors of each value and returns them in an array. To find the HCF, all that has to be done would be to compare the similar values in each array then multiply them together.
My code currently looks like this:
function hcf($x, $y) {
$hcf = array_product(array_intersect(prm_fac($x), prm_fac($y)));
if ($hcf != 0)
return $hcf;
else
return 1;
It's hard to explain, so I will show an example of the problem: If I try and find the HCF of 10 and 8, the prime factors of 10 will be 2, 5; the prime factors of 8 will be 2, 2, 2. The similar values in both arrays will be 2.
However, when I use the array_intersect function, it takes all the occurrences of 2, instead of just the single occurrence where it intersects. So instead of getting 2, I will get 2, 2, 2. How can I fix this problem?
Here is another example: I need to find the HCF of 4 and 16. The prime factors of 4 are 2, 2; the prime factors of 16 are 2, 2, 2, 2. I need to find the which values are the same for both arrays. If I use array_intersect on both arrays, it will give me 2, 2, 2, 2 instead of 2, 2. How do I fix this?
Here is the prm_fac function:
function prm_fac($n) {
$factors = array();
while ($n % 2 == 0) {
$factors[] = 2;
$n /= 2;
}
for ($i = 3; $i <= sqrt($n); $i += 2) {
while ($n % $i == 0) {
$factors[] = $i;
$n /= $i;
}
}
if ($n != 1)
$factors[] = $n;
return $factors;
}
Instead of array_intersect you could use this custom function instead, which will take into account that values can repeat, but will only take them when they repeat as many times in both arrays.
The rest of your code can stay:
function common_values($a, $b) {
return array_filter($a, function($v) use (&$b) {
return ($i = array_search($v, $b)) !== false && ($b[$i] = -1);
});
}
So, call it like this:
function hcf($x, $y) {
$hcf = array_product(common_values(prm_fac($x), prm_fac($y)));
if ($hcf != 0)
return $hcf;
else
return 1;
}
Explanation of the function
array_filter($a, ...) iterates over every element of $a, and for each of them calls the function provided in the second argument. If that function returns a truthy value, the corresponding element will be included (and only then) in the array that is returned by array_filter.
That inner return value is calculated as follows:
($i = array_search($v, $b)) finds the index where the value ($v) from $a occurs in $b. This index is assigned to the variable $i (on-the-fly). Then its value is compared with false, which tells us whether there was a match or not. If not, the rest of the expression is not evaluated because the && can never make the total expression true again. And so the return value is false, i.e. this value from $a is excluded (because it does not occur in $b).
In the other case, $i will not be false but an integer index, so the first comparison is true. Then the next part of the && is evaluated:
($b[$i] = -1)
The matching value in $b is wiped out so to make sure it cannot match again in any next iteration. It is wiped out with a negative value, as factors are expected to be always positive, and non-zero values also are truthy so that the return value of array_filter is true, i.e. this value from $a must be included in the result.
Notes and refereces
Note that HCF is also known as GCD. See also this solution to get it in a more direct way, or use gmp-gcd from the GMP extension.
You can use array_unique() to remove duplicates from the result array returned from array_intersect().
I think it would be better if you remove duplicates from the prm_fac() array. Something like :
$hcf = array_product(array_intersect(array_unique(prm_fac($x)), array_unique(prm_fac($y))));
Best practice would be to write it in you prm_fac function itself -
function prm_fac($val) {
.
.
.
return array_unique($factors);
}
We can make use of foreach to get the actual product array - This works for the egs I tried.
$product = array();
$array1 = prm_fac($x); //return the unique $x values
$array2 = prm_fac($y); //return the unique $y values
foreach ($array1 as $val1) {
foreach ($array2 as $val2) {
// Form the product array if the iterated values are present in the other array
if (in_array($val2, $array1) && in_array($val1, $array2)) {
$product[] = $val1;
$product[] = $val2;
}
}
}
Finally,
$hcf = array_product($product); //should give the proper product of values.

Specific data selection from php json

I have the following code :
$json = json_decode(URL, true);
foreach($json as $var)
{
if($var[id] == $valdefined)
{
$number = $var[count];
}
}
With json it looks like this :
[{"id":"1","count":"77937"},
{"id":"2","count":"20"},
{"id":"4","count":"25"},
{"id":"5","count":"11365"}]
This is what the array ($json) looks like after jsondecode
Array ( [0] => Array ( [id] => 1 [count] => 77937 ) [1] => Array ( [id] => 2 [count] => 20 ) [2] => Array ( [id] => 4 [count] => 25 ) [3] => Array ( [id] => 5 [count] => 11365) )
is there a way to say what is $json[count] where $json[id] = 3 for example
I'm not sure about a better way, but this is also fine, provided the JSON object is not huge. php is pretty fast when looping through JSON. If the object is huge, then you may want to split it. What I personally do is make my JSON into an array of normal objects, sort them, and then searching is faster on sorted items.
EDIT
Do json_decode($your_thing, true); set it true to make it an associative array, and then the id would be key and and the count would be value. After you do this, getting the value with the ID should really be easy and far more efficient.
If you change the way you build your json object to look like this :-
{"1":77937,"2":20,"4":25,"5":11365}
And then use the json_decode() parameter 2 set to TRUE i.e. turn the json into an array.
Then you have a usable assoc array with the ID as the key like so:
<?php
$json = '{"1":77937,"2":20,"4":25,"5":11365}';
$json_array = json_decode($json, TRUE);
print_r( $json_array);
?>
Resulting in this array
Array
(
[1] => 77937
[2] => 20
[4] => 25
[5] => 11365
)
Which you can do a simple
$number = json_array( $valdefined );
Or better still
if ( array_key_exists( $valdefined, $json_array ) ) {
$number = json_array( $valdefined );
} else {
$number = NULL; // or whatever value indicates its NON-EXISTANCE
}
Short answer to your initial question: why can't you write $json['count'] where $json['id'] = 3? Simply because PHP isn't a query language. The way you formulated the question reads like a simple SQL select query. SQL will traverse its indexes, and (if needs must) will perform a full table scan, too, its Structured Query Language merely enables you not to bother writing out the loops the DB will perform.
It's not that, because you don't write a loop, there is no loop (the absence of evidence is not the evidence of absence). I'm not going to go all Turing on you, but there's only so many things we can do on a machine level. On the lower levels, you just have to take it one step at a time. Often, this means incrementing, checking and incrementing again... AKA recursing and traversing.
PHP will think it understands what you mean by $json['id'], and it'll think you mean for it to return the value that is referenced by id, in the array $json, whereas you actually want $json[n]['id'] to be fetched. To determine n, you'll have to write a loop of sorts. Some have suggested sorting the array. That, too, like any other array_* function that maps/filters/merges means looping over the entire array. There is just no way around that. Since there is no out-of-the-box core function that does exactly what you need to do, you're going to have to write the loop yourself.
If performance is important to you, you can write a more efficient loop. Below, you can find a slightly less brute loop, a semi Interpolation search. You could use ternary search here, too, implementing that is something you can work on.
for ($i = 1, $j = count($bar), $h = round($j/2);$i<$j;$i+= $h)
{
if ($bar[++$i]->id === $search || $bar[--$i]->id === $search || $bar[--$i]->id === $search)
{//thans to short-circuit evaluation, we can check 3 offsets in one go
$found = $bar[$i];
break;
}//++$i, --$i, --$i ==> $i === $i -1, increment again:
if ($bar[++$i]->id > $search)
{// too far
$i -= $h;//return to previous offset, step will be halved
}
else
{//not far enough
$h = $j - $i;//set step the remaining length, will be halved
}
$h = round($h/2);//halve step, and round, in case $h%2 === 1
//optional:
if(($i + $h + 1) === $j)
{//avoid overflow
$h -= 1;
}
}
Where $bar is your json-decoded array.
How this works exactly is explained below, as are the downsides of this approach, but for now, more relevant to your question: how to implement:
function lookup(array $arr, $p, $val)
{
$j = count($arr);
if ($arr[$j-1]->{$p} < $val)
{//highest id is still less value is still less than $val:
return (object) array($p => $val, 'count' => 0, 'error' => 'out of bounds');
}
if ($arr[$j-1]->{$p} === $val)
{//the last element is the one we're looking for?
return $end;
}
if ($arr[0]->{$p} > $val)
{//the lowest value is still higher than the requested value?
return (object) array($p => $val, 'count' => 0, 'error' => 'underflow');
}
for ($i = 1, $h = round($j/2);$i<$j;$i+= $h)
{
if ($arr[++$i]->{$p} === $val || $arr[--$i]->{$p} === $val || $arr[--$i]->{$p} === $val)
{//checks offsets 2, 1, 0 respectively on first iteration
return $arr[$i];
}
if ($arr[$i++]->{$p} < $val && $arr[$i]->{$p} > $val)
{//requested value is in between? don't bother, it won't exist, then
return (object)array($p => $val, 'count' => 0, 'error' => 'does not exist');
}
if ($arr[++$i]->{$p} > $val)
{
$i -= $h;
}
else
{
$h = ($j - $i);
}
$h = round($h/2);
}
}
$count = lookup($json, 'id', 3);
echo $count['count'];
//or if you have the latest version of php
$count = (lookup($json, 'id', 3))['count'];//you'll have to return default value for this one
Personally, I wouldn't return a default-object if the property-value pair wasn't found, I'd either return null or throw a RuntimeException, but that's for you to decide.
The loop basically works like this:
On each iteration, the objects at offset $i, $i+1 and $i-1 are checked.
If the object is found, a reference to it is assigned to $found and the loop ends
The object isn't found. Do either one of these two steps:
ID at offset is greater than the one we're looking for, subtract step ($h) from offset $i, and halve the step. Loop again
ID is smaller than search (we're not there yet): change step to half of the remaining length of the array
A diagram will show why this is a more "clever" way of looping:
|==========x=============================|//suppose x is what we need, offset 11 of a total length 40:
//iteration 1:
012 //checked offsets, not found
|==========x=============================|
//offset + 40/2 == 21
//iteration 2:
012//offsets 20, 21 and 22, not found, too far
|==========x=============================|
//offset - 21 + round(21/2)~>11 === 12
//iteration 3:
123 //checks offsets 11, 12, 13) ==> FOUND
|==========x=============================|
assign offset-1
break;
Instead of 11 iterations, we've managed to find the object we needed after a mere 3 iterations! Though this loop is somewhat more expensive (there's more computation involved), the downsides rarely outweigh the benefits.
This loop, as it stands, though, has a few blind-spots, so in rare cases it will be slower, but on average it performs pretty well. I've tested this loop a couple of times, with an array containing 100,000 objects, looking for id random(1,99999) and I haven't seen it take more time than .08ms, on average, it manages .0018ms, which is not bad at all.
Of course, you can improve on the loop by using the difference between the id at the offset, and the searched id, or break if id at offset $i is greater than the search value and the id at offset $i-1 is less than the search-value to avoid infinite loops. On the whole, though, this is the most scalable and performant loopup algorithm provided here so far.
Check the basic codepad in action here
Codepad with loop wrapped in a function

create another multi dimensional array from an array

Suppose i have an array
$x= ('A'=>31, 'B'=>12, 'C'=>13, 'D'=>25, 'E'=>18, 'F'=>10);
I need to generate an array somewhat like this
$newx = (0 => array('A'=>31 , 'B' =>1) , 1 => array('B'=>11 , 'C' =>13 , 'D'=>8) , 2 =>array('D'=>17 , 'E'=>15) , 3=>array('E'=>3,'F'=>10);
Now in this case each value of $newx has to be = 32 and this is how it will work $x[A] = 31 , $x[B] = 12 so first of all we have to make the sum quantity to be 32 keeping the index same for the new array i.e
array(0=>array('A'=>31,'B'=>1) , 1=>array('B'=>11) )
the process should continue for each value of $x.
while I'm pretty sure this is a homework assignment and well, you really should provide code of your own, at least try to, I found the thing amusing so I went ahead and gave it a try. I guess I'll be downvoted for his and I probably do deserve it, but here goes anyway.
What you need to do is:
loop through your array,
determine the elements that give you 32 and then store that result in the final array.
subtract the value of the last element from your result from the corresponding element of your working array
shrink your array next by deleting the first elements until the very first element of the array you're still working with equals the last element your last result returned.
if your last result < 32, quit.
With this in mind, please try to find a solution yourself first and don't just copy-paste the code? :)
<?php
$x = array('A'=>31, 'B'=>12, 'C'=>13, 'D'=>25, 'E'=>18, 'F'=>10);
$result = array();
function calc($toWalk){
// walk through the array until we have gathered enough for 32, return result as an array
$result = array();
foreach($toWalk as $key => $value){
$count = array_sum($result);
if($count >= 32){
// if we have more than 32, subtract the overage from the last array element
$last = array_pop(array_keys($result));
$result[$last] -= ($count - 32);
return $result;
}
$result[$key] = $value;
}
return $result;
}
// logic match first element
$last = 'A';
// loop for as long as we have an array
while(count($x) > 0){
/*
we make sure that the first element matches the last element of the previously found array
so that if the last one went from A -> C we start at C and not at B
*/
$keys = array_keys($x);
if($last == $keys[0]){
// get the sub-array
$partial = calc($x);
// determine the last key used, it's our new starting point
$last = array_pop(array_keys($partial));
$result[] = $partial;
//subtract last (partial) value used from corresponding key in working array
$x[$last] -= $partial[$last];
if(array_sum($partial) < 32) break;
}
/*
reduce the array in size by 1, dropping the first element
should our resulting first element not match the previously returned
$last element then the logic will jump to this place again and
just cut off another element
*/
$x = array_slice($x , 1 );
}
print_r($result);

PHP code to find first covering prefix of an array

A non-empty zero-indexed array A consisting of N integers is given. The first covering prefix of array A is the smallest integer P such that $0 \leq P < N$ and such that every value that occurs in array A also occurs in sequence $A[0], A[1], \ldots, A[P]$.
For example, the first covering prefix of array A such that
A[0]=2 A[1]=2 A[2]=1 A[3]=0 A[4]=1
is 3, because sequence A[0], A[1], A[2], A[3] equal to 2, 2, 1, 0 contains all values that occur in array A.
Write a function
int ps(int[] A);
that given a zero-indexed non-empty array A consisting of N integers returns the first covering prefix of A. Assume that $N <= 1,000,000$. Assume that each element in the array is an integer in range [0..N-1].
For example, given array A such that A[0]=2 A[1]=2 A[2]=1 A[3]=0 A[4]=1
the function should return 3, as explained in the example above.
This is a very short solution. Pretty but won't scale well.
function ps($A) {
$cp = 0; // covering prefix
$unique = array_unique($A); // will preserve indexes
end($unique); // go to end of the array
$cp = key($unique); // get the key
return $cp;
}
Here's a simple way :
function covering_prefix ( $A ) {
$in=array();
$li=0;
$c=count($A);
for($i=0 ;$i<$c ; $i++){
if (!isset($in[$A[$i]])){
$in[$A[$i]]='1';
$li=$i;
}
}
return $li;
}
Here is a solution using ruby
def first_covering_prefix(a)
all_values = a.uniq
i = 0
a.each do |e|
all_values.delete(e)
if all_values.empty?
return i
end
i = i + 1
end
end
it's a 83% answer, because of use of in_array, a better solution already proposed by ronan
function solution($A) {
// write your code in PHP5
$in=array();
$li=0;
for ($i=0; $i < count($A); $i++) {
# code...
if (!in_array($A[$i], $in)){
$in[]=$A[$i];
$li=$i;
}
}
return $li;
}

Adding an element to the beginning of an array without changing other array keys [duplicate]

This question already has answers here:
How to insert an item at the beginning of an array in PHP?
(8 answers)
Closed 1 year ago.
How can I add an element to the beginning of array without changing array key values in PHP?
To keep numerical keys from being reindexed, you could simply add the arrays together.
Instead of:
array_unshift($arr1, $arr2)
try:
$arr1 = $arr2 + $arr1;
If you use self-assigned (e.g. literal) keys, array_unshift() will do it.
If you use auto-generated (numeric) keys, how should that work? Use '-1' as the new first key?
EDIT:
Thank you to JasonS for pointing out an error in this answer.
ANY numeric key will be re-indexed by array_unshift(), no matter if it was auto-generated or self-assigned - if it's numeric, it'll get scrambled. See the link to the documentation above for details.
Use array_unshift(). (As mentioned, it will keep your string keys intact, but not numeric keys).
try this:
function array_insert(&$array, $insert, $position = -1) {
$position = ($position == -1) ? (count($array)) : $position ;
if($position != (count($array))) {
$ta = $array;
for($i = $position; $i < (count($array)); $i++) {
if(!isset($array[$i])) {
die(print_r($array, 1)."\r\nInvalid array: All keys must be numerical and in sequence.");
}
$tmp[$i+1] = $array[$i];
unset($ta[$i]);
}
$ta[$position] = $insert;
$array = $ta + $tmp;
//print_r($array);
} else {
$array[$position] = $insert;
}
//ksort($array);
return true;
}
Just a quick note for if you wish to use this in a loop...
As stated here: http://jp2.php.net/manual/en/function.array-unshift.php
array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.
TO give you an idea of how slow this is, we wrote some benchmark code (based on http://pastebin.com/Jad5TjsQ), and here is how it looks
mt#wizcorp-dev2:~/dev/test$ for d in arrayFillBrackets.php arrayFillPush.php arrayFillUnshift.php arrayFillPushReverse.php ; do cat $d; php $d; done
<?php
require "benchmark.php";
function ArrayFillBrackets()
{
$result = array();
for($i = 0; $i < 10000; $i++) $result[] = $i;
return $result;
}
$result = array();
$result[10]['ArrayFillBrackets'] = Benchmark('ArrayFillBrackets', null, 10);
!!! Benchmarking function ArrayFillBrackets for 10 iteration (args:null)...
===================
Results:
===================
time total: 0.02686286
time min: 0.00198293
time max: 0.0058589
time avg: 0.002686286
memory total: 0
memory min: 0
memory max: 0
memory avg: 0
<?php
require "benchmark.php";
function ArrayFillPush()
{
$result = array();
for($i = 0; $i < 10000; $i++) array_push($result, $i);
return $result;
}
$result = array();
$result[10]['ArrayFillPush'] = Benchmark('ArrayFillPush', null, 10);
!!! Benchmarking function ArrayFillPush for 10 iteration (args:null)...
===================
Results:
===================
time total: 0.03958679
time min: 0.003757
time max: 0.00485086
time avg: 0.003958679
memory total: 0
memory min: 0
memory max: 0
memory avg: 0
<?php
require "benchmark.php";
function ArrayFillUnshift()
{
$result = array();
for($i = 0; $i < 10000; $i++) array_unshift($result, $i);
return $result;
}
$result = array();
$result[1]['ArrayFillUnshift'] = Benchmark('ArrayFillUnshift', null, 1);
!!! Benchmarking function ArrayFillUnshift for 1 iteration (args:null)...
===================
Results:
===================
time total: 3.62487912
time min: 3.62487912
time max: 3.62487912
time avg: 3.62487912
memory total: 0
memory min: 0
memory max: 0
memory avg: 0
<?php
require "benchmark.php";
function ArrayFillPushReverse()
{
$result = array();
for($i = 0; $i < 10000; $i++) array_push($result, $i);
return array_reverse($result);
}
$result = array();
$result[10]['ArrayFillPushReverse'] = Benchmark('ArrayFillPushReverse', null, 10);
!!! Benchmarking function ArrayFillPushReverse for 10 iteration (args:null)...
===================
Results:
===================
time total: 0.05071593
time min: 0.00475311
time max: 0.00560999
time avg: 0.005071593
memory total: 108
memory min: 0
memory max: 24
memory avg: 10.8
mt#wizcorp-dev2:~/dev/test$
Please note that all tests are 10 * 10,000, except the array_unshift that runs 1 * 10,000 (was quite tired of waiting)... So again, don't use array_shift in iteration, as reversing the array only once costs almost nothing instead.
Adding my own (redundant) answer, because I tried to edit Martin's answer, using his original example, but it was rejected by others (not Martin). Maybe they didn't review the history of his answer, as I'm using his original example array and problem. Here is my rejected edit.
Kevin Wentworth's answer is correct.
Expanding on that answer using the original example from Martin's answer, if you have an array
$a = [1 => a, 2 => b, 5 => e, 6 => f, 8 => h, 9 => i];
and you want to take the last three items and prepend them to this same array, then you could do the following.
$a = array_slice($a, -3, null, true) + $a;
The resulting array is
array (6 => 'f', 8 => 'h', 9 => 'i', 1 => 'a', 2 => 'b', 5 => 'e',)
Notes
The true argument to array_slice preserves numeric keys (no such parameter exists for array_unshift).
Although array_slice doesn't remove anything from the original array, because of the behaviour of the + operator on arrays, the last three items are cancelled out.
From the docs for the + array operator
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
array_unshift will not modify non numeric keys
Use array_unshift(); this will help u in adding element
Well, if you are doing what I am doing and creating a select form using results from the DB with indexes being the ids from the DB table, but want to add say "Any..." to the array with an index of 0, simply create the array variable with that item first, then populate the remaining values from the database. No need to unshift or order things after the database call.

Categories