How to have a simple array without key from an array key=>value?

32,803

Solution 1

If you want the without Key You should use array_values() and json_encode()(It means convert to string) the array like

$arr = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
print_r(json_encode(array_values($arr)));

OutPut:

["35","37","43"]

Solution 2

No need to create a function for it, there is an inbuilt function array_values() that does exactly same as required.

From the docs:

Return all the values of an array

Example:

$arr = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
print_r(array_values($arr)); // Array ( [0] => 35 [1] => 37 [2] => 43 )

Solution 3

You're looking for array_values which will return just the values from the key/value pairs.

$arr = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$arrVals = array_values($arr);

The code behind it is much the same as you'd expect, with a foreach looping through and pushing the result to a new array.

Solution 4

Try this -

$arrs = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$array = (array_values($arrs)); 

echo "<pre>";
print_r($array);
Share:
32,803
user9417455
Author by

user9417455

Updated on June 09, 2021

Comments

  • user9417455
    user9417455 almost 3 years

    I have an array like this : array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); and would like to get only my values, for example here :

    simpleTab=array("35","37","43");

    or otherwise like this, it should be better for me to get a list :

    simpleList=["35";"37";"43"]
    

    I'm creating a function because I'll need it several times so here it is :

    $simpleArray=array(); //don't know if this should be array, i'd like to have a list
    
    foreach($valueAssoc as $key => $value{//array_push($simpleArray,$value);//NO it returns an array with keys 0 , 1 , etc
        //$simpleArray[]=$value; //same ! I don't want any keys
    
        //I want only an array without any index or key "tableau indexé sans clef"
        echo $value;
        //would like to have some method like this :
        $simpleArray.add($value);//to add value in my list -> can't find the php method
    
  • Rahul
    Rahul about 6 years
    its same answer which is given below
  • tkamath99
    tkamath99 over 3 years
    I was converting an array to Object. I typecasted the array but it returns with index position like [0]: {"key": "value" }. How can i remove the index [0]
  • Dharmendra Singh
    Dharmendra Singh over 3 years
    Its good to use predefined function with lesser amount of code. Your answer is good but with using function is best.
  • MonTea
    MonTea almost 3 years
    u missed a ; behind the array_push line
  • Admin
    Admin almost 3 years
    I changed it... Thank you
  • radren
    radren almost 3 years
    what is $key_name ?