简体   繁体   中英

Why doesn't my PHP foreach work?

$start = true;
$new = "";
foreach($array as $val)
{
    if($start = true && $val != " ")
    {
        $start = false;
        $new .= strtoupper($val);
    }
    elseif($val == " ")
    {
        $new .= " ";
        $start = true;
    }
    else
    {
        $new .= strtolower($val);
    }
    $start = false;
}

Basically what happens is $start NEVER becomes false AND everything becomes capitalized. So it looks like the first if IS running, but for some reason NEVER SETS $start to false .

$start = true is an assignment, not a comparison. Use == .

You're using a single equals in your test, which means "assignment". You probably meant == (equality), but in this case, with booleans, you don't need to compare at all:

$start = true;
$new = "";
foreach($array as $val)
{
    if($start && $val != " ") // <-- remove the = true here
    {
        $start = false;
        $new .= strtoupper($val);
    }
    elseif($val == " ")
    {
        $new .= " ";
        $start = true;
    }
    else
    {
        $new .= strtolower($val);
    }
    $start = false;
}

Right now, it's getting interpreted as "Set $start to true && $val != " " " - definitely not what you intended.

I cannot stress it enough: use the yoda condition

if(true == $var)

or generally:

if(CONSTANT == $VARIABLE)

and not

if($VARIABLE == CONSTANT) //which you'd wrongly type as "="

PHP would have told you what went wrong in that case - no matter how tired you are.

Looking for this bug (it happens to the best of the best too) is frustrating.

Let the tool (PHP) be supportive to you, don't make it work against you.

That was on a more general note. As for your problem, it's doable with a one-liner:

<?php
$array = "hEllo woRlD";

var_dump(ucwords(strtolower($array)));

$start = true && $val != " " means:

$start = (true && $val != " ")
$start = ($val != " ")
$start = !($val == " ") // $start is true except when $val is a single space.

I believe you meant $start == true .

Are you just trying to upper case the first character of every word? If so, look into ucwords .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM