Web Hosting Talk







View Full Version : substr an array


-Edward-
09-26-2007, 11:54 AM
Hi Folks,

I'm having a little trouble breaking down this array:


$images = array
(
'44' => 'img.gif',
'45' => 'file.swf',
);

This is inside a function called GetMy.

I've created another function that I want to grab the final 3 letters of what the array displays.

So, if it ends in .gif it displays:

This is an image

and if it ends in .swf it displays:

This is a flash movie

Here's my function:

function wts( ) {

$get = GetMy();

$display = substr($get, 0, 3);

if ($display = "gif") {

echo "Its a gif image";

} else {

echo "Its a flash movie";

}

}


It shows the following though:

img.gif img.gifIts a gif image

Whether it's an img or an swf file, Can anyone help?

foobic
09-26-2007, 12:23 PM
1. We'd need to see the whole of function GetMy - at a guess it's echoing a result instead of returning it as you want.

2. Be real careful about the difference between:
if ($display = "gif") {
and
if ($display == "gif") {
The first is an assignment - it's always true, no matter what value $display had before.

-Edward-
09-26-2007, 12:33 PM
Sorry,

It is actually:

function wts( ) {

$get = GetMy();

$display = substr($get, 0, 3);

if ($display == "gif") {

echo "Its a gif image";

} else {

echo "Its a flash movie";

}

}


Here's my GetMy() function:

function GetMy() {

$default_image = "../xadax.gif";

$dept = $_GET['department'];


$images = array
(
'44' => 'img.gif',
'45' => 'file.swf',
);

if(strlen($images[$dept]) > 0)
{

echo $images[$dept];
}

elseif ($pimages[$product_code])
{
echo $pimages[$product_code];
}
else
{

echo "$default_image";
}

isurus
09-26-2007, 01:27 PM
As foobic said: your GetMy() function is echoing a result instead of returning it.

Try this:


function GetMy()
{

$default_image = "../xadax.gif";

$dept = $_GET['department'];

$images = array
(
'44' => 'img.gif',
'45' => 'file.swf'
);

if(strlen($images[$dept]) > 0)
{
return( $images[$dept] );
}

elseif ($pimages[$product_code])
{
return( $pimages[$product_code] );
}
else
{
return( $default_image );
}
}

(I'm assuming that $pimages and $product_code are defined elsewhere)

You are also grabbing the first 3 characters of the string, not the last 3:
$display = substr($get, 0, 3);If you want to grab the last three characters you should use this:
$display = substr($get, -3);It may also be worth you checking for it being an unknown file type:
eg
switch( $display )
{
case 'gif':
echo "gif image";
break;
case 'swf':
echo "flash movie";
break;
default:
echo "unknown";
break;
}HTH,

Simon

-Edward-
09-26-2007, 02:38 PM
That appears to of done the trick! changing display to:

$display = substr($get, -3);

Thank you.