Last active
December 18, 2015 20:39
-
-
Save m8rge/5842003 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// we have some model attributes in array | |
$modelAttributes = array( | |
'first', | |
'second' | |
); | |
// also, we have new attributes in same array. This can occure if your html form contains elements with names: | |
// Model[Attribute][] = first | |
// Model[Attribute][] = second | |
// Model[Attribute][newAttributes][] = third | |
// Model[Attribute][newAttributes][] = fourth | |
$modelAttributes['newAttributes'] = array( | |
'third', | |
'fourth' | |
); | |
foreach ($modelAttributes as $id => $entry) { | |
if ($id == 'newAttributes') { | |
foreach ($entry as $newAttribute) { | |
echo "creating $newAttribute\n"; | |
} | |
} else { | |
echo "display $entry\n"; | |
} | |
} | |
/* | |
produces output: | |
--- | |
Warning: Invalid argument supplied for foreach() on line 20 | |
display second | |
creating third | |
creating thourth | |
--- | |
Why? I expect those output: | |
display first | |
display second | |
creating third | |
creating thourth | |
--- | |
'first' element passes ($id == 'newAttributes') comparison, because comparison looks like (0 == 'newAttributes'). | |
Php cast string as int value, as cannot find numeric characters in begining of string. | |
So, | |
0 == "0" // true | |
0 == "qwe1" // true | |
0 == "qwe" // true | |
0 == "1" // false | |
0 == "1qwe" // false | |
Conclusion: | |
If you using html naming schema like I described above, make sure type case from integer to string like that: | |
(string)$id == 'newAttributes' | |
*/ |
Если не newAttributes
, а просто любой массив?
if (is_array($entry)) { ..
if (is_array($entry) && $id === 'newAttributes') { ..
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
а как насчет $id === 'newAttributes'