Page 1 of 1

curious array behavior

Posted: Tue Jun 18, 2013 11:56 am
by rhecker
In the following code snippet, an array is built based on the value of the variable 'days'. So the expected result for the given value "ace" should be
Array
(
[0] => 0
[1] => 2
[2] => 4
)
. . .however, if you try it, you will see that it ignores the first key->value pair unless value days is preceeded by an arbitrary character, such as the 'z' I added to the commented out line. I'm just trying to understand why I have to add that extra character for the array to populate correctly. Thoughts?

Code: Select all

$days = "ace";
if ($days) {
//$days = "z$days";
if (strpos($days, 'a')){
$weekset[]=0;}
if (strpos($days, 'b')){
$weekset[]=1;}
if (strpos($days, 'c')){
$weekset[]=2;}
if (strpos($days, 'd')){
$weekset[]=3;}
if (strpos($days, 'e')){
$weekset[]=4;}
if (strpos($days, 'f')){
$weekset[]=5;}
if (strpos($days, 'g')){
$weekset[]=6;}
echo "<pre>";
print_r($weekset);
echo "</pre>";

Re: curious array behavior

Posted: Tue Jun 18, 2013 12:16 pm
by AbraCadaver
I can't really decipher what you want to accomplish here, but: if (strpos($days, 'a')){ evaluates to false because it returns 0 which is the position of 'a' within $days.

Try:

Code: Select all

if (strpos($days, 'a') !== false){

Re: curious array behavior

Posted: Tue Jun 18, 2013 12:56 pm
by AbraCadaver
Also, just for fun:

Code: Select all

$days = 'ace';
$lookup_array = range('a', 'g');
$days_array = str_split($days);

$weekset = array_flip(array_intersect($lookup_array, $days_array));
print_r($weekset);
//or
$weekset = array_keys(array_intersect($lookup_array, $days_array));
print_r($weekset);
[text]Array
(
[a] => 0
[c] => 2
[e] => 4
)[/text]
--or
[text]Array
(
[0] => 0
[1] => 2
[2] => 4
)[/text]

Re: curious array behavior

Posted: Tue Jun 18, 2013 1:16 pm
by rhecker
Thanks Abracadaver,

Your code was more elegant and terse than what I was doing, and it accomplishes the same thing.