Change a value in an array in a loop - php

I have an array, I need to loop through and change it's value:
foreach ($input['qualification'] as &$_v) {
$_v = ucwords($_v);
}
But this only works for the first item in the array. When I remove the ampersand it loops through the entire array, but obviously the changes are not made.

If you're trying to apply a function to all of the values in an array I would recommend using array_map() instead.
Applies the callback to the elements of the given arrays
$qualifications = array_map('ucwords', $input['qualification']);
Demo

$input['qualification'] = array('high school', 'inter school', 'bachelor of scinece', 'master of science');
foreach ($input['qualification'] as &$_v) {
$_v = ucwords($_v);
}
echo "<pre>";print_r($input['qualification']);

Here is how to do it more slowly, with explicit reference to the index, in case your actual programming task requires the value of the index.
https://eval.in/436395
$input = array('juggling','french','math');
foreach ($input as $i=>$v) {
$input[$i] = ucwords($v);
}

Related

array_key_exist() with array as key

I'm trying to check if in an array there is any value of another array. The function array_key_exist() looks like what I'm searching for, but I don't understand how to give the key value at the function as an array. Here's the code:
$risultato_query_controllo_numero = mysql_query($query_controllo_numero);
$voucher_esistenti = array();
while(($row = mysql_fetch_assoc($risultato_query_controllo_numero))) {
$voucher_esistenti[] = $row['numero'];
}
Which populates the first array with numbers:
$voucher = range($numero, $numero + $quantita);
Which populates the second array with numbers.
What I need to do now is to check if any of the value in $voucher is present in $voucher_presenti.
You can use the array_intersect function:
$overlap = array_intersect($voucher, $voucher_presenti);
You can find more examples in the documentation.
You could use the in_array() function to get the result you are looking for.
$arrayOne = range(1, 10);
$arrayTwo = range(5, 15);
foreach ($arrayOne as $value) {
if (in_array($value, $arrayTwo)) {
echo 'value '.$value.' is in the first and second array.<br />';
}
}
Resources
in_array() - Manual
in_array could be a good solution for your need, for example you can assign $voucher_esistenti only when you have a new value in the sql row.
$risultato_query_controllo_numero=mysql_query($query_controllo_numero);
$voucher_esistenti=array();
while(($row = mysql_fetch_assoc($risultato_query_controllo_numero))){
if(!in_array($row['numero'], $voucher_esistenti) {
$voucher_esistenti[] = $row['numero'];
}
} // this solution isn't optimal, because you will check subarrays with each new value
There's a better way to achieve that, by using a hashmap which has a complexity of O(1) ( best complexity :) )
$risultato_query_controllo_numero=mysql_query($query_controllo_numero);
$voucher_esistenti=array();
while(($row = mysql_fetch_assoc($risultato_query_controllo_numero))){
// here is what we changed, instead of key = value, we actually append keys
if(!isset($voucher_esistenti[$row['numero']]) {
$voucher_esistenti[$row['numero']] = true;
}
}
/*
The second implementation is a lot faster due to the algorithm, but you will have to change the reading of $voucher_esistenti array. */

Remove first element from simple array in loop

This question has been asked a thousand times, but each question I find talks about associative arrays where one can delete (unset) an item by using they key as an identifier. But how do you do this if you have a simple array, and no key-value pairs?
Input code
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $banana) {
// do stuff
// remove current item
}
In Perl I would work with for and indices instead, but I am not sure that's the (safest?) way to go - even though from what I hear PHP is less strict in these things.
Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably an empty array).
1st method (delete by value comparison):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $key=>$banana) {
if($banana=='big_banana')
unset($bananas[$key]);
}
2nd method (delete by key):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
unset($bananas[0]); //removes the first value
unset($bananas[count($bananas)-1]); //removes the last value
//unset($bananas[n-1]); removes the nth value
Finally if you want to reset the keys after deletion process:
$bananas = array_map('array_values', $bananas);
If you want to empty the array completely:
unset($bananas);
$bananas= array();
it still has the indexes
foreach ($bananas as $key => $banana) {
// do stuff
unset($bananas[$key]);
}
for($i=0; $i<count($bananas); $i++)
{
//doStuff
unset($bananas[$i]);
}
This will delete every element after its use so you will eventually end up with an empty array.
If for some reason you need to reindex after deleting you can use array_values
How about a while loop with array_shift?
while (($item = array_shift($bananas)) !== null)
{
//
}
Your Note: Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably
an empty array).
Simply use unset.
foreach ($bananas as $banana) {
// do stuff
// remove current item
unset($bananas[$key]);
}
print_r($bananas);
Result
Array
(
)
This question is old but I will post my idea using array_slice for new visitors.
while(!empty($bananas)) {
// ... do something with $bananas[0] like
echo $bananas[0].'<br>';
$bananas = array_slice($bananas, 1);
}

How to declare, insert and iterate a php associative array with an associative array as value?

I need to work with a hashtable which values can store variables like:
$numberOfItems
$ItemsNames
If I ain't wrong, that would mean another hash like array as value.
What should be the right syntax for inserting and iterating over it?
Is anything like:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
valid?
if there's no chance to have collusion in item name, you can use the name in key
$hash[$ItemsName] = $numberOfItems;
in the other case, use an integer for example as a key, then the different "attributes" you want as keys for the 2nd array
$hash[$integer]["count"] = $numberOfItems;
$hash[$integer]["name"] = $name;$
Then, for iterating (1st case):
foreach ($hash as $name => $number) {
echo $number;
echo $name;
}
or, 2nd case
foreach ($hash as $item) {
echo $item["name"];
echo $item["count"];
}
To create php array, which can be a hash table, you can do:
$arr['element'] = $item;
$arr['element'][] = $item;
$arr['element'][]['element'] = $item;
Other way:
$arr = array('element' => array('element' => array(1)));
To iterate over it use foreach loop:
foreach ($items as $item) {
}
It's also possible to create nested loops.
About your case:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
I would do:
$hash['anyKey']['numberOfItems'] = 15;
$hash['anyKey']['ItemsNames'] = array('f','fw');

creating variable names from an array list

How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
//create a new variable called $elem1 (or $other or $elemother, etc.)
//and assign it some default value 1
}
foreach ($myarray as $name) {
$$name = 1;
}
This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.
goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:
extract(array_flip($myarray));
This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:
echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'
Wildly useful.
Something like this should do the trick
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
$myVars[$arr] = 1;
}
Extract ( $myVars );
What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).
Use array_keys($array)
i.e.
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
$myarray[$singleKeyName] = 1;
}
http://www.php.net/manual/en/function.array-keys.php

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories