Tag Archives: PHP

Check if object is in (multidimensional) array?

Python:

>>> arr = [[1,3],[2,4]]
>>> 2 in [x[0] for x in arr]
True
>>> 3 in [x[0] for x in arr]
False

PHP:

$arr = [[1,3],[2,4]];
var_dump(in_array(1, array_map(function($x){return $x[0];},$arr), true));
var_dump(in_array(3, array_map(function($x){return $x[0];},$arr), true));

Gives

bool(true)
bool(false)

Adding true for “strict mode”, to prevent false positives (1 == true, 0 == false)

Java:

int[][] arr = {{1,3},{2,4}};
System.out.println(Arrays.stream(arr).map(x -> x[0]).collect(Collectors.toList()).contains(1));
System.out.println(Arrays.stream(arr).map(x -> x[0]).collect(Collectors.toList()).contains(3));

Gives

true
false

Converting arrays to/from strings

Found myself using these functions in various prints to interfaces and whatnot, so here’s the elegant ways of creating comma-separated strings. The added bonus is that this method allows for separation of data in for-loops. Early on I’d usually add a separation manually in each step of the loop and finish by removing the extra separation at the end.

Python:

string = ",".join(['1','2','3','4'])
array = string.split(",")

PHP:

echo($str = implode(",", [1,2,3,4,5]));
var_dump(explode(",",$str));

Java:

With Apache Commons:

StringUtils.join(new String[]{"1","2","3"}, ',');

In Android:

TextUtils.join(new String[]{"1","2","3"}, ',');

Without requires a bit of setup with StringBuilder and a for-loop, unless you use JDK8:

String[] array = {"1", "2", "3", "4", "5"};
System.out.println(String.join(",",array));

Check out the new StringJoiner class for some interesting helper functions.

Basic API: Redirecting URLs

In the thetvdb.com-example we can see that the URL is formed as if that XML-file is stored in the data/series/267440/all/ subdirectory. This is not the case, much like it isn’t the case that all the articles in WordPress are stored in their own directories. Instead the server is most likely using a redirect mechanism using the .htaccess-file.

In our new basic API we’ll do the same thing. By placing a .htaccess-file in the “mediainfo/api” directory on our server we can tell the web server how to handle requests in that subdirectory. In this case the file will look like this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ../apihandler.php?path=$1&%{QUERY_STRING} [L]

The RewriteCond-lines tell us that if the requested filename is not a file (!-f) or a directory (!-d) we will redirect the request to ^(.*)$ ../apihandler.php?path=$1&%{QUERY_STRING} [L]. The $1 will contain the excess path, in this case “search/a movie title”, and the QUERY_STRING is the standard GET-variables (may in fact not be necessary, verify)

This is the first step in creating an API that looks clean. By splitting the path and removing the forward slash we can handle requests differently based on the fake directories being requested.