Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the keys and values of an array without index [closed]

I want to extract data from an array (original array with key and value). After I extract the array, I want two new arrays, the first one with just the keys, the second one with just the values, and both without indexes (see code example).

// original array 
$array = array(
    "name1"=>500
   ,"name2"=>400
   ,"name3"=>300
   ,"name4"=>200
   ,"name5"=>100
);

// after extraction
$array1 = array('name1','name2','name3','name4','name5');
$array2 = array(500,400,300,200,100);

// not like this
// $array1 = array(0=>'name1',1=>'name2',2=>'name3',3=>'name4',4=>'name5);
// $array2 = array(0=>500,1=>400,2=?300,3=>200,4=>100);
like image 372
Liuqing Hu Avatar asked Apr 08 '13 03:04

Liuqing Hu


People also ask

How do you access keys and values in an array?

Array elements can be accessed using the array[key] syntax. ); var_dump($array["foo"]);

Can we search array value without index number?

When searching an array without an index, use the status (on or off) of the resulting indicators to determine whether a particular element is present in the array. Searching an array without an index can be used for validity checking of input data to determine if a field is in a list of array elements.

Which function do you use to remove an element from an array without changing the index value?

In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically.

How can I remove a key and its value from an associative array?

Method 1: Using unset() function: The unset() function is used to unset a key and its value in an associative array. print_r( $arr ); ?> Method 2: Using array_diff_key() function: This function is used to get the difference between one or more arrays.


2 Answers

$array1 = array_keys($array);
$array2 = array_values($array);

well, you can read here.

In computer science, an array data structure or simply an array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored so that the position of each element can be computed from its index tuple by a mathematical formula.

like image 55
Afriyandi Setiawan Avatar answered Sep 19 '22 13:09

Afriyandi Setiawan


$keys = array_keys($array);
$values = array_values($array);

Note however that array(0=>'item') and array('item') are exactly identical as far as PHP is concerned. There is no such thing as a php array item without an index. If you do not supply an index PHP will silently add a numeric index.

like image 21
Francis Avila Avatar answered Sep 20 '22 13:09

Francis Avila