Reputation: 1222
I have this array (which eventually doesn't work, and gives illegal offset type error.
protected $files = [
['jpeg', 'bmp'] => 'images',
['mp4', 'avi'] => 'videos',
]
This method is what I want.
public function getType($extension){
// my question is related to this method right here.
}
This is the test area.
var_dump( (new FileDetector())->getType('jpeg') ); // this should return 'image'
So the idea right here is searching the array of $files
.
However the first error I get while writing things like that is 'Illegal offset type
'.
I cannot create an array which looks like this:
[
['jpg', ...] => 'images',
['avi', ...] => 'videos'
]
It works the other way around like:
[
'images' => ['jpg', ...],
'videos' => ['avi', ...],
]
Can you explain to me why the first one doesn't work, or a hint regarding that error so I can look online etc.?
Second is my main question, there are lots of ways to achieve what I want, but I want the best practice and this one to me looks like the cleanest way.
Upvotes: 1
Views: 68
Reputation: 7485
If you swap your keys and values (you can't use an array for a key in a Php array), we can iterate through the list until we find the extension you are after.
<?php
$type_extensions = [
'images' => ['jpeg','bmp'],
'videos' => ['mp4','avi']
];
$get_type_from_extension = function($extension) use ($type_extensions) {
foreach($type_extensions as $type => $extensions) {
if(in_array($extension, $extensions))
return $type;
}
};
var_dump($get_type_from_extension('mp4'));
var_dump($get_type_from_extension('ogg'));
Output
string 'videos' (length=6)
null
Upvotes: 0
Reputation: 1324
you are trying to set up an associative array with an array as a key!
Man page: http://php.net/manual/en/language.types.array.php
The key can either be an integer or a string. The value can be of any type.
NOTE:
PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays.
try this instead:
protected $files = [
'jpeg' => 'images',
'bmp'=> 'images',
'mp4' => 'videos',
'avi' => 'videos'
];
Upvotes: 1
Reputation: 448
For the first part of the question, php arrays are associative arrays, meaning they can have only one value as key. Associative arrays are key value pairs, where for one key there exists multiple values but not wise versa. Therefore you are getting error for this
[
['jpg', ...] => 'images',
['avi', ...] => 'videos'
]
and not for this
[
'images' => ['jpg', ...],
'videos' => ['avi', ...],
]
better approach to deal with this would be
case 1:
[
'images' => ['jpg', ...],
'videos' => ['avi', ...],
]
or case 2
[
'jpg' => ['images'],
'bmp' => ['images'],
'avi' => ['videos'],
'mp4' => ['videos'],
]
now as you can see, case one is compact,not redundant, so go ahead with case 1 as a better approach among 2.
Hope this helps.
Upvotes: 2