Page 1 of 1

Bump up variables to replace empty vals, variable variables?

Posted: Sun May 16, 2010 3:46 pm
by batfastad
Hi everyone
This has been driving me nuts over the weekend, trying to find the best way to do this.

I need to take 3 telephone, 3 fax numbers (and 3 emails and websites also) and store them in a MySQL table.
The variables are numbered tel1, tel2, tel3, fax1, fax2, fax3 and if one is empty, then bump the others up in its place.
So if tel1 is empty then tel2 and tel3 each get bumped up one place.
And if tel1 has a value, tel2 is empty, then move tel3 to tel2 etc.
... And the same for the fax nos.

Can anyone think of a better way to do this other than nesting a whole bunch of ifs...elseifs?
We might want to add more values in the future so normally I would do this with related tables in our DB but we're going to be building some queries with a plenty of joins so I'd like to keep them in the same table.

Just wondering if anyone can suggest a quick/short way of doing this?

Cheers, B

Re: Bump up variables to replace empty vals, variable variab

Posted: Sun May 16, 2010 4:12 pm
by requinix
You can make an array and pass it through array_filter() to remove empty values then array_values() to reindex the array.

Code: Select all

$phones = array("555-1234", "", "555-1212");
$phones = array_values(array_filter($phones)); // 0=>555-1234, 1=>555-1212
list($p1, $p2, $p3) = $phones + array("", "", ""); // p1=555-1234, p2=555-1212, p3=empty

Re: Bump up variables to replace empty vals, variable variab

Posted: Mon May 17, 2010 2:02 pm
by batfastad
Awesome stuff. array_values() was what I wanted!
Thanks for the help :lol: