0

I have

$whitelist = array ("a", "b", "c", "d");

a global whitelist of allowed values of a certain $_POST variable. I use the following expression to obtain an enlarged whitelist with a certain extra value ("e")

array_merge($whitelist, array("e"))

(I feed this to a whitelisting function). But it seems rather complicated.

I am wondering if there is a better way to do this? I.e. I am looking for an expression returning an array with an added element.

I am aware of the following two constructions

$whitelist[] = "e";

and

array_push($whitelist, "e");

but both are procedural, modify the original array and neither of them could be used in an expression.

A possible expression would also be

$whitelist + array((max(array_keys($whitelist))+1)=>"e")

but it is even more cumbersome than the array_merge method.

4
  • 3
    So for what are you looking for?
    – Rizier123
    Apr 26, 2015 at 17:21
  • A simpler way than array_merge (probably, there is none).
    – apurkrt
    Apr 26, 2015 at 17:23
  • 1
    I think you already got the simplest with array_merge()
    – Rizier123
    Apr 26, 2015 at 17:24
  • Reading php.net/manual/en/function.array-push.php it seems that the following is better than using array_merge: $tmp = $whitelist; $tmp[] = "e"; and subsequently working with $tmp instead of an expression (there is no overhead for calling a function when using $array[] = )
    – apurkrt
    Apr 26, 2015 at 18:57

1 Answer 1

0

Actually this is possible, though only with an inconvenient condition:

PHP defines the union array operator ($a + $b, where both $a and $b are arrays) which does what you are looking for. Check this page for an explanation: http://php.net/manual/en/language.operators.array.php

However there is one annoying condition: the arrays key sets must be disjoint. Which actually makes sense, once you think about it. Bot for your example this could be a little inconvenient: "simple" scalar arrays do by default not have disjoint key sets, unless you take specific care of that.

3
  • 1
    Thank you, but I already know about that option - see the end of my question.
    – apurkrt
    Apr 26, 2015 at 17:27
  • Well, your approach in that part of the question is cumbersome because you try to combine the union statement with the creation of a suitable crafted array. But that is not the fault of the union operator. It is an issue of how you construct your arrays... If you really want to define your own operator, then php simply is the wrong base you chose. You should try a hard typed language which allows operator overloading.
    – arkascha
    Apr 26, 2015 at 17:29
  • Basically, in the end I was just brainstorming. I currently use the array_merge way. Thanks again for your reply.
    – apurkrt
    Apr 26, 2015 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.