php get array value from array

array_values

(PHP 4, PHP 5, PHP 7, PHP 8)

array_values — Выбирает все значения массива

Описание

Список параметров

Возвращаемые значения

Возвращает индексированный массив значений.

Примеры

Пример #1 Пример использования array_values()

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 25 notes

Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the ‘foreach’ ordering:

Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.

Doing this will cause PHP exceeds the momory limits:

Most of the array_flatten functions don’t allow preservation of keys. Mine allows preserve, don’t preserve, and preserve only strings (default).

echo ‘var_dump($array);’.»\n»;
var_dump($array);
echo ‘var_dump(array_flatten($array, 0));’.»\n»;
var_dump(array_flatten($array, 0));
echo ‘var_dump(array_flatten($array, 1));’.»\n»;
var_dump(array_flatten($array, 1));
echo ‘var_dump(array_flatten($array, 2));’.»\n»;
var_dump(array_flatten($array, 2));
?>

If you are looking for a way to count the total number of times a specific value appears in array, use this function:

I needed a function that recursively went into each level of the array to order (only the indexed) arrays. and NOT flatten the whole thing.

Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:

/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>

A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298

same array_flatten function, compressed and preserving keys.

/**********************************************
*
* PURPOSE: Flatten a deep multidimensional array into a list of its
* scalar values
*
* array array_values_recursive (array array)
*
* WARNING: Array keys will be lost
*
*********************************************/

Non-recursive simplest array_flatten.

A modification of wellandpower at hotmail.com’s function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.

Please note that ‘wellandpower at hotmail.com’s recursive merge doesn’t work. Here’s the fixed version:

The function here flatterns an entire array and was not the behaviour I expected from a function of this name.

I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.

In order to do this, you will want this function:

function array_values_recursive($array) <
$temp = array();

Hopefully this will assist.

Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus «preserving keys» may have different interpretations. Ivan’s function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.

/*
* Flattening a multi-dimensional array into a
* single-dimensional one. The resulting keys are a
* string-separated list of the original keys:
*
* a[x][y][z] becomes a[implode(sep, array(x,y,z))]
*/

Источник

PHP get array value from function

I have the following function:

5 Answers 5

check below solution

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

And you also having return statement before this line.Try to return at once.In your case after the first return statement it won’t return the second value.

If your IF condition not satisfies then at least it should be initialized with empty value or as an array.

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

Plus: second return will never be reached.

If you want to return both values you could do it like this:

preg_replace() returns an array if the subject parameter is an array, or a string otherwise. And use preg_match instead.

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

Something wrong in your logic. I’ll try to rewrite.

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

Not the answer you’re looking for? Browse other questions tagged php or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

array

(PHP 4, PHP 5, PHP 7, PHP 8)

array — Создаёт массив

Описание

Создаёт массив. Подробнее о массивах читайте в разделе Массивы.

Список параметров

Наличие завершающей запятой после последнего элемента массива, несмотря на некоторую необычность, является корректным синтаксисом.

Возвращаемые значения

Примеры

Последующие примеры демонстрируют создание двухмерного массива, определение ключей ассоциативных массивов и способ генерации числовых индексов для обычных массивов, если нумерация начинается с произвольного числа.

Пример #1 Пример использования array()

Пример #2 Автоматическая индексация с помощью array()

Результат выполнения данного примера:

Этот пример создаёт массив, нумерация которого начинается с 1.

Результат выполнения данного примера:

Как и в Perl, вы имеете доступ к значениям массива внутри двойных кавычек. Однако в PHP нужно заключить ваш массив в фигурные скобки.

Пример #4 Доступ к массиву внутри двойных кавычек

Примечания

Смотрите также

User Contributed Notes 38 notes

As of PHP 5.4.x you can now use ‘short syntax arrays’ which eliminates the need of this function.

So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an label. So, with this function, if only a single array is passed to the function (i.e. «arrayToSelect($stateList)») then it will simply spit out a bunch of » » elements. On the other hand, if two arrays are passed to it, the second array becomes a «key» for translating the first array.

Here’s a further example:

$countryList = array(
‘CA’ => ‘Canada’,
‘US’ => ‘United States’);

$stateList[‘CA’] = array(
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘MB’ => ‘Manitoba’,
‘NB’ => ‘New Brunswick’,
‘NL’ => ‘Newfoundland/Labrador’,
‘NS’ => ‘Nova Scotia’,
‘NT’ => ‘Northwest Territories’,
‘NU’ => ‘Nunavut’,
‘ON’ => ‘Ontario’,
‘PE’ => ‘Prince Edward Island’,
‘QC’ => ‘Quebec’,
‘SK’ => ‘Saskatchewan’,
‘YT’ => ‘Yukon’);

$stateList[‘US’] = array(
‘AL’ => ‘Alabama’,
‘AK’ => ‘Alaska’,
‘AZ’ => ‘Arizona’,
‘AR’ => ‘Arkansas’,
‘CA’ => ‘California’,
‘CO’ => ‘Colorado’,
‘CT’ => ‘Connecticut’,
‘DE’ => ‘Delaware’,
‘DC’ => ‘District of Columbia’,
‘FL’ => ‘Florida’,
‘GA’ => ‘Georgia’,
‘HI’ => ‘Hawaii’,
‘ID’ => ‘Idaho’,
‘IL’ => ‘Illinois’,
‘IN’ => ‘Indiana’,
‘IA’ => ‘Iowa’,
‘KS’ => ‘Kansas’,
‘KY’ => ‘Kentucky’,
‘LA’ => ‘Louisiana’,
‘ME’ => ‘Maine’,
‘MD’ => ‘Maryland’,
‘MA’ => ‘Massachusetts’,
‘MI’ => ‘Michigan’,
‘MN’ => ‘Minnesota’,
‘MS’ => ‘Mississippi’,
‘MO’ => ‘Missouri’,
‘MT’ => ‘Montana’,
‘NE’ => ‘Nebraska’,
‘NV’ => ‘Nevada’,
‘NH’ => ‘New Hampshire’,
‘NJ’ => ‘New Jersey’,
‘NM’ => ‘New Mexico’,
‘NY’ => ‘New York’,
‘NC’ => ‘North Carolina’,
‘ND’ => ‘North Dakota’,
‘OH’ => ‘Ohio’,
‘OK’ => ‘Oklahoma’,
‘OR’ => ‘Oregon’,
‘PA’ => ‘Pennsylvania’,
‘RI’ => ‘Rhode Island’,
‘SC’ => ‘South Carolina’,
‘SD’ => ‘South Dakota’,
‘TN’ => ‘Tennessee’,
‘TX’ => ‘Texas’,
‘UT’ => ‘Utah’,
‘VT’ => ‘Vermont’,
‘VA’ => ‘Virginia’,
‘WA’ => ‘Washington’,
‘WV’ => ‘West Virginia’,
‘WI’ => ‘Wisconsin’,
‘WY’ => ‘Wyoming’);

Источник

Get column values from an associative array in php

I have an array of form:

I want output like this :

EDIT:

Can this be achieved??

7 Answers 7

You cannot do this since you can’t have duplicate keys in an array.

Answer after your edit:

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

You can achieve your (edited) question like this:

If you want to array with in the array means, surely it will generated with index key, like this

Your output will be,

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

you can try this one

Output :

This is not possible, because you cannot have multiple elements of the same key in an associative array.

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

With array_map (http://3v4l.org/v8Y8Z):

With array_column (http://3v4l.org/ohnGu):

Note: array_column doesn’t make subarrays with the first_name key.

Not the answer you’re looking for? Browse other questions tagged php associative-array or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Get the index of a certain value in an array in PHP

I want to get the index for a given value (i.e. 1 for string2 and 2 for string3 )

All I want is the position of the strings in the array

How to achieve this?

12 Answers 12

array_search is the way to do it.

You could loop over the array manually and find the index but why do it when there’s a function for that. This function always returns a key and it will work well with associative and normal arrays.

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

If you’re only doing a few of them (and/or the array size is large), then you were on the right track with array_search:

If you want all (or a lot of them), a loop will prob do you better:

Other folks have suggested array_search() which gives the key of the array element where the value is found. You can ensure that the array keys are contiguous integers by using array_values() :

You said in your question that array_search() was no use. Can you explain why? What did you try and how did it not meet your needs?

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

// or considering your array structure:

The problem is that you don’t have a numerical index on your array.
Using array_values() will create a zero indexed array that you can then search using array_search() bypassing the need to use a for loop.

Could you be a little more specific?

works fine for me. Are you trying to accomplish something more complex?

This code should do the same as your new routine, working with the correct multi-dimensional array..

Try the array_keys PHP function.

array_search should work fine, just tested this and it returns the keys as expected:

Or for the index, you could use

You’ll have to create a function for this. I don’t think there is any built-in function for that purpose. All PHP arrays are associative by default. So, if you are unsure about their keys, here is the code:

php get array value from array. Смотреть фото php get array value from array. Смотреть картинку php get array value from array. Картинка про php get array value from array. Фото php get array value from array

Not the answer you’re looking for? Browse other questions tagged php arrays or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *