How to match a key value in for other key value inside the same array?

151 Views Asked by At

I'm sorry because i know that is probably a noob question, but i have so much work to do that i cant finish my PHP learning process.

Let's say i have a variable for the file extension and an array in PHP like that:

$fileExt = ".php";

$mainNav = array(

    "page01" => array (

        "id"    =>  "value",
        "name"  =>  "value",
        "title" =>  "value",
        "url"   =>  need same "id" value + $fileExt

    ),

    "page02" => array (

        "id"    =>  "value",
        "name"  =>  "value",
        "title" =>  "value",
        "url"   =>  need same "id" value + $fileExt

    ),
);

But I like that instead of hard coding the value for "url", it match the value of the key "name" + the file extension that i already have in a variable just in case i need to change it later.

3

There are 3 best solutions below

0
On
$url = $page01['url'].$fileExt;
2
On

This should do the job:

$fileExt = ".php";

$var['page01'] => array (
    "id"    =>  "inicio",
    "name"  =>  "Inicio",
    "title" =>  "Incio - Cerartec",
);

$var['page01']['url'] = $var['page01']['name'] . $fileExt;
0
On

There's a few ways to accomplish this, below is probably the easiest without seeing all the code you are using.

$fileExt = ".php";

$mainNav = array(

   "page01" => array (
      "id"    =>  "idvalue",
      "name"  =>  "value",
      "title" =>  "value"
   ),

   "page02" => array (
      "id"    =>  "idvalue2",
      "name"  =>  "value",
      "title" =>  "value"
   )
);

foreach($mainNav as $key => $value)
{
   $mainNav[$key]["url"] = $value["id"] . $fileExt;
}

I'm also thinking that this stuff is being stored in a database? If so just add a field for the url and when you insert the page go ahead and do the url at the same time.