Reputation: 773
I found this questions which helps me with what I am doing, but the problem that I'm running into is - I keep getting an Undefined index error for this $images = glob($imagesDir. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
Here is my full code (it is a part of an if/elseif):
elseif($result['avatar_type'] == 'Random'){
$images = array(); //Initialize once at top of script
$imagesDir = 'avatar/random/';
if(count($images)==0){
$images = glob($imagesDir. '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
shuffle($images);
}
$avatar = array_pop($images);
}
What I am trying to do is if the database has the avatar_type set to Random then display a random image from the Random directory, but like I said above I keep getting an Undefined index error.
Does anyone see anything wrong with what I am doing and why I would be receiving this error?
Upvotes: 0
Views: 758
Reputation: 1186
A few suggestions:
This isn't neccessary as glob will return an array:
$images = array(); //Initialize once at top of script
see http://php.net/manual/en/function.glob.php
This will cause a warning (but not an error) if glob previously returned false:
$avatar = array_pop($images);
http://php.net/manual/en/function.array-pop.php
If you make sure to check return types in the manual you will know what to check for in your code.
if (empty($var))
is great because it checks for false, null, or undefined without throwing an error.
Also, as array_pop returns the last element and glob is likely to return the elements in the same order it will not be as random as array_rand would be.
$avatarKey = array_rand($images, 1); //return 1 random result's key
$avatar = $images[$avatarKey]; //set the random image value (accessed w/ the rand key)
Your error message shouldn't be caused by the glob line, it's actually probably from this:
elseif($result['avatar_type'] == 'Random'){
If avatar_type isn't set on the result array or the result array is empty you will get an undefined index.
To prevent that error from happening you would check the array exists before trying to access the avatar_type key:
function example:
function getRandomAvatar($result)
{
if (empty($result) || empty($result['avatar_type'])) {
return; //quit execution if the data is bad
}
//rest of code here -
}
inline code example:
if (empty($result) || empty($result['avatar_type'])) {
//do nothing, render an error, whatever - stops execution of the next statement
} else {
//this code will only run if $result and $result['avatar_type
//are set and wont cause errors
if ('$result['avatar_type'] == 'Random') {
//do code here
Your error should have a line number. Check that line and the line right before it.
Upvotes: 1