Why is my PHP foreach not working?

$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 $startNEVER becomes falseAnd everything becomes capitalized. So this is like starting ifIS for the first time, but for some reason NEVER SETS $start- false.

0
source share
5 answers

I can't stress this enough: use the yoda condition

if(true == $var)

or even:

if(CONSTANT == $VARIABLE)

but not

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

PHP would tell you what went wrong in this case - no matter how tired you are.

Looking for this mistake (this happens to the best of the best too) is disappointing.

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

. , :

<?php
$array = "hEllo woRlD";

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

$start = true - , . ==.

+1

Your test uses one equal, which means "assignment." You probably meant ==(equality), but in this case using 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;
}

At the moment, it is interpreted as “Install $startin true && $val != " "” - definitely not what you intended.

+1
source

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

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

I suppose you mean it $start == true.

0
source

Are you just trying to use uppercase as the first character of each word? If yes, review ucwords.

0
source

All Articles