0

I would like to create an array with the values from another array "$array" but as keys...

$array= array
  (
  array(
    "name"       => "name", 
    "text"       => "Name",
    "type"       => "input", 
    "data-error" => "Please enter the client's name.", 
    "required"   => "required"),
  array(
    "name"       => "address", 
    "text"       => "Address",
    "type"       => "textarea", 
    "data-error" => "Please enter the address.", 
    "required"   => "required"),
  array(
    "name"       => "email", 
    "text"       => "Email",
    "type"       => "input", 
    "data-error" => "Please enter an email address", 
    "required"   => "required"),
  array(
    "name"       => "telephone", 
    "text"       => "Telephone",
    "type"       => "text", 
    "data-error" => "Please enter the telephone number", 
    "required"   => "required")
);

Output array should look like:

$new_array = ["name", "address", "email", "telephone"];

how can I create this new array with the information given in $array? It's always the value where key = "name" (first element) in each of the sub-arrays in the Multidimensional array. $array

thank you

1
  • Your question is somewhat unclear. If nfnneil's answer solves your issue please award it the green tick, if not you will probably need to clarify your question with an edit. As I read it (a few times now), you could be asking how to create an array with subarrays that hold all values per each attribute. Is that true? like: $new_array("name"=>array("name","address","email","telephone"),"text"=>... Clarifying your question will not only help SO members that wish to answer your question, but future researchers that have the same issue. Commented Apr 2, 2017 at 22:40

1 Answer 1

1

You can iterate over an array using a foreach loop. array_push will be used to append an element to theend of $finalArray. Finally, I use var_dump to display the contents on the page (for testing purposes).

$finalArray = Array();
foreach ($array as $key => $value) {
    array_push($finalArray, $value['name']);
}
var_dump($finalArray);

Technically, you don't need the $key for this loop, but I wanted to show you how to use the foreach. If you want to do it the short hand way, simply remove the $key =>. Like, as follows:

foreach ($array as $value) {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.