PHP. How Can I check ALL array
I have this code:
$data[1] = "blablabla";
$data[2] = "blablablabla";
if (strle开发者_StackOverflown($data) < 10)
{
// doing...
}
In this code I want to check all elements from array. How to do it?
foreach ($data as $element) {
if (strlen($element) < 10) {
// Do something
}
}
If you want to modify the data, use a reference (add a &
before $element
):
foreach ($data as &$element) {
if (strlen($element) < 10) {
// Do something to $element
$element = "something else";
}
}
If you don't want to use references directly, you can use a standard for
loop with an indexer:
for ($i = 0; $i < count($data); $i++) {
if (strlen($data[$i]) < 10) {
// Do something with $data[$i]
$data[$i] = "something else";
}
}
Use array_walk function of PHP. There are many examples on the linked PHP manual page.
Also take a look at array_map and array_filter functions.
for ($i = 0;$i < count($data);$i++){
if (strlen($data[$i]) < 10){
// process
}
}
精彩评论