I have a code like this:
<?php
$kode ["J"]= array (20, C, D, F);
$kode ["K"]= array (50, B, G, U);
$kode ["T"]= array (70, V, W);
function kota ($start, $end){
if (is_array($kode)) {
foreach ($kode as $kota => $path){
if ($kota=$end) {
for ($i=1; $i < count ($kota); $i++){
$jalur=$start.$path[$i];
}
}
}
return $jalur;
}
}
$start = "J";
$end = "T";
$hasil=kota ($start, $end);
echo "".$hasil;
?>
I want the output to be J-V-W
I don’t know what is wrong, can anyone help me? please…
Your code has lots of issues
As others pointed out, in
if ($kota=$end) {, you are assigning$endto$kotaand always returntruei.e. the code in the IF clause always executePHP has function scope. Simply put, variables declared inside a function cannot be used outside, and vice versa. Use parameters to pass your
$kodeinto the function.Use of bare strings i.e.
VandWin$kode ["T"]= array (70, V, W);and other places. This is highly recommended against, and PHP does warn you about this.As other pointed out,
$jalur=$start.$path[$i];would overwrite$jalurevery time. The for-loop outside is meaningless. You would use.=the append-to operator. Note that you also need to initialize your variable before using this operator.$kotais always a string in your code, because in aforeachloop, the variable before=>symbol means get the key of the array, and array keys can only be either String or integer. That said,for ($i=1; $i < count ($kota); $i++){is meaningless becausecount($kota)cannot be greater than 1 – your for loop actually never runs.This is blatantly meaningless to append a variable with an empty string as in
echo "".$hasil;I guess this is what you want.
This code give you the string which starts with
$startand all other elements except the first element in$kode[$end]