Skip to content

Instantly share code, notes, and snippets.

@m8rge
Last active December 18, 2015 20:39
Show Gist options
  • Save m8rge/5842003 to your computer and use it in GitHub Desktop.
Save m8rge/5842003 to your computer and use it in GitHub Desktop.
<?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'
*/
@DarkAiR
Copy link

DarkAiR commented Jun 23, 2013

а как насчет $id === 'newAttributes'

@efureev
Copy link

efureev commented Sep 15, 2015

Если не 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