-3

I want to be able to create an array like the below:

$array = array('one' => '1', 'two' => '2');

but by using code like this:

$array=array();
$array = 'one'

$array = 'two'

but how do i create the second part of each item in the array?

2

3 Answers 3

2

You can try this, and if you have more key you can add into $a array

$a = array('one', 'two');
$array = array();
foreach ($a as $index => $value) {
    $array[$value] = ++$index;
}
Sign up to request clarification or add additional context in comments.

Comments

2

try this:

<?php 
$array=array();
$array['one'] =1 ;

$array['two'] =2 ;
print_r($array);

?>

NOTE: if you want array with numeric key in your implementation you can do this:

<?php 
    $array=array();
    $array[1] ='one' ;
    $array[] ='two' ;
    $array[] ='three' ;
    print_r($array);

    ?>

7 Comments

ha ha ha ha.. your suggestion array results like $array[0] = 'one', $array[1] = 'two'.
@ Vinoth Babu that is an optional part if he want to implement.answer for him is first one.
yes boss. optional part you given will not map 1 with one and 2 with two. thats what i said. anyhow fine.. :)
@VinothBabu i never meant 1 with one i meant dynamic index creation.
@VinothBabu but if you get it like that,it means i have not explained properly so let me change it.
|
0

try this

<?php 
$array=array();
$array['one'] = 1;

$array['two'] = 2;
print_r($array);

?>

3 Comments

Exact copy from @suchit! Don't do that please
it was not copied, suchit's code contained some error which he has fixed in the edit
i am not sure weather it is copied... just see two answer within few seconds...BTW ... no problem..with this also

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.