I've got this PHP code:
$array = array( 0 => 'brick', 1 => 'brick', 2 => 'window' );
$array_2 = array( 0 => 'brick', 1 => 'brick', 2 => 'door' );
foreach ( $array as $key => $value)
{
$my_variable = array();
foreach ( $array_2 as $key_2 => $value_2 )
{
$my_variable[ $value_2 ] = !isset( $my_variable[ $value_2 ] ) ?
$key_2 :
'several';
echo var_dump( $my_variable[ $value_2 ] ) . '<br/>';
echo var_dump( $my_variable[ $value_2 ] == 'several' ) . '<br/><br/>';
}
}
It outputs:
int(0)
bool(true)
string(7) "several"
bool(true)
int(2)
bool(false)
int(0)
bool(true)
string(7) "several"
bool(true)
int(2)
bool(false)
int(0)
bool(true)
string(7) "several"
bool(true)
int(2)
bool(false)
The strange part of it is this one (the first output shouln't be true as it's not equal to 'several'
, as it says it's value is indeed equal to 0
):
int(0)
bool(true)
string(7) "several"
bool(true)
Because of this condition:
$my_variable[ $value_2 ] == 'several'
So, the question is: does anyone know why is this happening? Is there something wrong in my code I'm ignoring...?
On the other hand: if I change the array ordering (make it to start from 1, not from 0), it magicaly starts to work (outpust the correct logic):
$array = array( 1 => 'brick', 2 => 'brick', 3 => 'window' );
$array_2 = array( 1 => 'brick', 2 => 'brick', 4 => 'door' );
It's also possible to switch the condition (without a need to change array numbering) to:
!is_string( $my_variable[ $value_2 ] )
It than maybe outputs the correct logic, but the the mystery (why PHP outputs true
if it should output false
) still remains. And I'm afraid it could bring some troubles in the future when the code will be in the production. I'm also not happy from not knowing whether I'm possibly doing something wrong here...?
Based on the comments I would like to make some statements, just to make clear why I'm doing some things in the code above the way I do:
I'm looping inside other loop in order to chache the values from the
array_2
, (just in my real code, not here, code here is just substraction of it, to make question simpler, sorry for the confusion).I'm echoing
var_dump()
in order to be able to add the<br/>
string (thanks for<br/>
, I totaly overlooked it.) - correctedYes,
$my_variable = null;
should be$my_variable = array();
, but again only here (in the real code I assignarray()
later and only if needed). - corrected
`. – gen_Eric Sep 15 '16 at 16:06