Replace non-specified array values with 0 - php

I want to replace all array values with 0 except work and home.
Input:
$array = ['work', 'homework', 'home', 'sky', 'door']
My coding attempt:
$a = str_replace("work", "0", $array);
Expected output:
['work', 0, 'home', 0, 0]
Also my input data is coming from a user submission and the amount of array elements may be very large.

A bit more elegant and shorter solution.
$aArray = array('work','home','sky','door');
foreach($aArray as &$sValue)
{
if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}
The & operator is a pointer to the particular original string in the array. (instead of a copy of that string)
You can that way assign a new value to the string in the array. The only thing you may not do is anything that may disturb the order in the array, like unset() or key manipulation.
The resulting array of the example above will be
$aArray = array('work','home', 0, 0)

A loop will perform a series of actions many times. So, for each element in your array, you would check if it is equal to the one you want to change and if it is, change it. Also be sure to put quote marks around your strings
//Setup the array of string
$asting = array('work','home','sky','door')
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work' || $asting[$i] == 'home')
$asting[$i] = 0;
}
Here is some suggested reading:
http://www.php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/language.control-structures.php
But if you are struggling on stuff such as looping, you may want to read some introductory programming material. Which should help you really understand what's going on.

A bit other and much quicker way, but true, need a loop:
//Setup the array of string
$asting = array('bar', 'market', 'work', 'home', 'sky', 'door');
//Setup the array of replacings
$replace = array('home', 'work');
//Loop them through str_replace() replacing with 0 or any other value...
foreach ($replace as $val) $asting = str_replace($val, 0, $asting);
//See what results brings:
print_r ($asting);
Will output:
Array
(
[0] => bar
[1] => market
[2] => 0
[3] => 0
[4] => sky
[5] => door
)

An alternative using array_map:
$original = array('work','home','sky','door');
$mapped = array_map(function($i){
$exclude = array('work','home');
return in_array($i, $exclude) ? 0 : $i;
}, $original);

you may try array_walk function:
function zeros(&$value)
{
if ($value != 'home' && $value != 'work'){$value = 0;}
}
$asting = array('work','home','sky','door','march');
array_walk($asting, 'zeros');
print_r($asting);

You can also give array as a parameter 1 and 2 on str_replace...

Just a small point to the for loop. Many dont realize the second comparing task is done every new iteration. So if it was a case of big array or calculation you could optimize loop a bit by doing:
for ($i = 0, $c = count($asting); $i < $c; $i++) {...}
You may also want to see http://php.net/manual/en/function.array-replace.php for original problem unless the code really is final :)

Try This
$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
$key = array_search($val, $your_array);
$your_array[$key] = 0;
}
print_r($your_array);

There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise. For best maintainability, I recommend separating your list of targeted string as a lookup array. By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.
Code: (Demo)
$array = ['work', 'homework', 'home', 'sky', 'door'];
$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);
foreach ($array as &$v) {
$v = $lookup[$v] ?? 0;
}
var_export($array);
Output:
array (
0 => 'work',
1 => 0,
2 => 'home',
3 => 0,
4 => 0,
)
You can very easily, cleanly extend your list of targeted strings by merely extending $keep.
If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)
var_export(
array_map(fn($v) => $lookup[$v] ?? 0, $array)
);

this my final code
//Setup the array of string
$asting = array('work','home','sky','door','march');
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
$asting[$i] = 20;
} elseif($asting[$i] == 'home'){
$asting[$i] = 30;
}else{
$asting[$i] = 0;
}
echo $asting[$i]."<br><br>";
$total += $asting[$i];
}
echo $total;

Related

PHP find max between variables

I'm trying to find out wich variable is bigger (those are all integers):
<?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;
echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
I tried with max but it gives the value and not the $varName.
I want to get the name of the variable and if there are two that are equal I need both.
Thanks for the help.
As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...
$confronto = [
'ectoA' => $ectoA,
'ectoB' => $ectoB,
'endoA' => $endoA,
'endoB' => $endoB,
'mesoA' => $mesoA,
'mesoB' => $mesoB,
];
$result= array_keys($confronto,max($confronto));
$neurotipo = $result[0];
echo $neurotipo;
I want endoA and endoB to be identified...
You can define an array instead, or compact your variables into an array:
//$array = array('ectoA'=>3,'ectoB'=>5,'mesoA'=>0,'mesoB'=>4,'endoA'=>11,'endoB'=>11);
$array = compact('ectoA','ectoB','mesoA','mesoB','endoA','endoB');
$result = array_keys($array, max($array));
Then compute the max() of that array and use array_keys() to search for the max number and return the keys.
print_r($result);
Yields:
Array
(
[0] => endoA
[1] => endoB
)
I would definitely recommend using an array. Then you can do something like this:
$my_array = array(3, 5, 0, 4, 11, 11);
$maxIndex = 0;
for($i = 1; $i < count($my_array); $i++) {
if($my_array[$i] > $my_array[$maxIndex])
$maxIndex = $i;
}
Another option with array keys would be:
$my_array = array("ectoA" => 3, "ectoB" => 5, "mesoA" => 0, "mesoB" => 4, "endoA" => 11, "endoB" => 11);
$maxIndex = "ectoA";
while($c = current($my_array)) {
$key = key($my_array);
if($my_array[$key] > $my_array[$maxIndex])
$maxIndex = $key;
next($my_array);
}
Note: Code not tested, but should be the gist of what needs to be done
use the array like this
<?php
$value= array (
"ectoA" =>3,
"ectoB"=>5,
"mesoA"=>0,
"mesoB"=>4,
"endoA"=>11,
"endoB"=>11);
$result= array_keys($value,max($values))
print_r($result);
?>
As per the documentation, Since the two values are equal, the order they are provided determines the result $endoA is the biggest here.
But I am not sure your intention is to find the biggest value or which variable is the highest
Your code seems to be a working one.
But it would print for you the value of the maximum number, not the name of the variable.
To have the name of the variable at the end you should add some additional code like:
$max = (max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
if($max == $ectoA) echo "ectoA";
if($max == $ectoB) echo "ectoB";
// ... same goes for other variables
But working with an array would be the most proper solution.

Push static value into another array at every nth position

I have an array:
$names = [
"Ayush" , "Vaibhav", "Shivam",
"Hacker", "Topper", "ABCD",
"NameR", "Tammi", "Colgate",
"Britney", "Bra", "Kisser"
];
And I have another variable
$addthis = "ADDTHIS";
How to make an array from these two so that after every three items in $names, the value of $addthis is added. So, I want this array as result from these two.
$result = [
"Ayush", "Vaibhav", "Shivam", "ADDTHIS",
"Hacker", "Topper", "ABCD", "ADDTHIS",
"NameR", "Tammi", "Colgate", "ADDTHIS",
"Britney", "Bra", "Kisser"
];
"Oneliner", just for fun:
$new = array_reduce(
array_map(
function($i) use($addthis) { return count($i) == 3 ? array_merge($i, array($addthis)) : $i; },
array_chunk($names, 3)
),
function($r, $i) { return array_merge($r, $i); },
array()
);
Maybe an easier to understand solution:
// the parameters
$names = array( "Ayush" , "Vaibhav", "Shivam", "Hacker", "Topper",
"ABCD", "NameR", "Tammi", "Colgate", "Britney",
"Bra", "Kisser");
$addThis = 'ADDTHIS';
$every = 3;
// how often we need to add this
$count = ceil(count($names) / $every) - 1;
for ($i = 0; $i < $count; $i++) {
array_splice($names, $i * ($every + 1) + $every, 0, $addThis);
}
array_splice is exactly for modifying arrays (removing or adding items), preserves existing keys and is not doing any other operation on the array.
While other answers are for sure valid as well this should be the fastest and cleanest solution.
Another oneliner ;)
$result = call_user_func_array(
'array_merge', array_map(function($v) use ($addthis) {
return $v + [4 => $addthis];
}, array_chunk($names, 3))
); array_pop($result);
Demo
I have the ANSWER for anyone curious, I've just done a function that randomizes an array.
function randomize($array){
$randomized=array(); //start a new array
foreach ($array as $key=>$val){ ///loop thru the array we randomize
if($key % 2 == 0){ ////if the key is even
array_push($randomized,$val);///push to back
}else{ ////if the key is odd
array_unshift($randomized,$val); ///push to front
}
}
return $randomized;
}///randomize
Basically what we are doing is creating a new randomized array, looping through the array we pass, tracking an interator and as we loop thru if the key is even we send that array value to the back, if its odd we send that to the front.
I concur with #iRaS's answer that it will be more direct/efficient to make iterated element insertions in a loop. I interpret the question as requiring an element to be inserted after every 10 elements -- in other words, if the array has exactly 20 elements, then 2 elements should be inserted. One after the 10nth element, then one after the 20th element.
By iterating from the back of the array, you can avoid keeping track of previously injected elements (which effectively push out the desired position of subsequently injected elements). I didn't use this approach while crafting a dynamic approach for a similar question.
Use a modulus-based calculation to determine the last insertion position, then decrement the position variable by the $every variable.
To test the accuracy of my snippet, just add and remove elements in the input array.
Code: (Demo)
$names = [
"Ayush" , "Vaibhav", "Shivam",
"Hacker", "Topper", "ABCD",
"NameR", "Tammi", "Colgate",
"Britney"//, "Bra"//, "Kisser"
];
$addThis = 'ADDTHIS';
$every = 3;
for (
$count = count($names), $pos = $count - ($count % $every);
$pos > 0;
$pos -= $every
) {
array_splice($names, $pos, 0, $addThis);
}
var_export($names);
Output:
array (
0 => 'Ayush',
1 => 'Vaibhav',
2 => 'Shivam',
3 => 'ADDTHIS',
4 => 'Hacker',
5 => 'Topper',
6 => 'ABCD',
7 => 'ADDTHIS',
8 => 'NameR',
9 => 'Tammi',
10 => 'Colgate',
11 => 'ADDTHIS',
12 => 'Britney',
)
P.S. If you don't want to add the extra tail element (the array shouldn't end with an "ADDTHIS" element), then use this code as the first parameter of the for():
$count = count($names), $pos = $count - (($count % $every) ?: $every);
$result = array();
$cnt = 0;
foreach ($names AS $val) {
$result[] = $val;
if ($cnt >=3) {
$result[] = $addthis;
$cnt = 0;
}
$cnt++;
}
Loop through and use modulo for checking for 3. element:
After that use splice to insert an element between two element
foreach($result as $k=>$value){
if(($k+1)%3==0){
array_splice($arrayvariable, $k+1, 0, "ADDTHIS");
}
}
One thing you do not want to do is assume that every key in your array is numeric and that it accurately represents the offset of each element. This is wrong, because PHP arrays are not like traditional arrays. The array key is not the offset of the element (i.e. it does not determine the order of elements) and it does not have to be a number.
Unfortunately, PHP arrays are ordered hashmaps, not traditional arrays, so the only way to insert a new element in the middle of the map is to create a brand new map.
You can do this by using PHP's array_chunk() function, which will create a new array of elements, each containing up to a designated number of elements, form your input array. Thus we create an array of arrays or chunks of elements. This way you can iterate over the chunks and append them to a new array, getting your desired effect.
$names = array( "Ayush" , "Vaibhav", "Shivam", "Hacker", "Topper",
"ABCD", "NameR", "Tammi", "Colgate", "Britney",
"Bra", "Kisser");
$addthis = "ADDTHIS";
$result = array();
foreach (array_chunk($names, 3) as $chunk) { // iterate over each chunk
foreach ($chunk as $element) {
$result[] = $element;
}
// Now push your extra element at the end of the 3 elements' set
$result[] = $addthis;
}
If you wanted to preserve keys as well you can do this....
$names = array( "Ayush" , "Vaibhav", "Shivam", "Hacker", "Topper",
"ABCD", "NameR", "Tammi", "Colgate", "Britney",
"Bra", "Kisser");
$addthis = "ADDTHIS";
$result = array();
foreach (array_chunk($names, 3, true) as $chunk) { // iterate over each chunk
foreach ($chunk as $key => $element) {
$result[$key] = $element;
}
// Now push your extra element at the end of the 3 elements' set
$result[] = $addthis;
}
This perserves both order of the elements as well as keys of each element. However, if you don't care about the keys you can simply use the first example. Just be careful that numeric keys in order will cause you a problem with the second approach since the appended element in this example is assuming the next available numeric key (thus overwritten on the next iteration).

Remove Array value

[0] => LR-153-TKW
[1] => Klaten
[2] => Rectangular
[3] => 12x135x97
I have an array looking like this. and I want to completely remove 12x135x97 to the mother array so how would i do this?
You can use unset($arr[3]);. It will delete that array index. Whenever you want to delete an array value, you can use PHP unset() method.
As you were asked into your comment:
basically i just want to remove all index that have "X**X" this pattern digit 'x' digit
Here is the code that you can use:
$arr = array("LR-153-TKW", "Klaten", "Rectangular", "12x135x97", "xxxx");
$pattern_matched_array = preg_grep("/^[0-9]+x[0-9]+x[0-9]*/", $arr);
if(count($pattern_matched_array) > 0)
{
foreach($pattern_matched_array as $key => $value)
{
unset($arr[$key]);
}
}
print_r($arr);
PHP has unset() function. You can use it for deleting a variable or index of array.
unset($your_var[3]);
See http://php.net/manual/en/function.unset.php
You have many options:
if you know the array key then you can do this
unset($arrayName[3]);
or if it's always at the end of your array
array_pop($arrayName);
this will remove the last value out of your array
Use unset, to find it you can do this:
for($i = 0; $i < count($array); $i++){
if($i == "12x135x97"){
unset($array[i]);
break;
}
}
Unless you know the key, in which case you can do:
unset($array[3]);
its not the most time efficient if you array is thousands of items long, but for this job it will suffice.
To turn it into a method, would make for better coding.
function removeItem($item){
for($i = 0; $i < count($array); $i++){
if($i == $item){
unset($array[i]);
break;
}
}
return $array;
}
and call it like:
removeItem("12x135x97");

how to skip elements in foreach loop

I want to skip some records in a foreach loop.
For example, there are 68 records in the loop. How can I skip 20 records and start from record #21?
Five solutions come to mind:
Double addressing via array_keys
The problem with for loops is that the keys may be strings or not continues numbers therefore you must use "double addressing" (or "table lookup", call it whatever you want) and access the array via an array of it's keys.
// Initialize 25 items
$array = range( 1, 25, 1);
// You need to get array keys because it may be associative array
// Or it it will contain keys 0,1,2,5,6...
// If you have indexes staring from zero and continuous (eg. from db->fetch_all)
// you can just omit this
$keys = array_keys($array);
for( $i = 21; $i < 25; $i++){
echo $array[ $keys[ $i]] . "\n";
// echo $array[$i] . "\n"; // with continuous numeric keys
}
Skipping records with foreach
I don't believe that this is a good way to do this (except the case that you have LARGE arrays and slicing it or generating array of keys would use large amount of memory, which 68 is definitively not), but maybe it'll work: :)
$i = 0;
foreach( $array as $key => $item){
if( $i++ < 21){
continue;
}
echo $item . "\n";
}
Using array slice to get sub part or array
Just get piece of array and use it in normal foreach loop.
$sub = array_slice( $array, 21, null, true);
foreach( $sub as $key => $item){
echo $item . "\n";
}
Using next()
If you could set up internal array pointer to 21 (let's say in previous foreach loop with break inside, $array[21] doesn't work, I've checked :P) you could do this (won't work if data in array === false):
while( ($row = next( $array)) !== false){
echo $row;
}
btw: I like hakre's answer most.
Using ArrayIterator
Probably studying documentation is the best comment for this one.
// Initialize array iterator
$obj = new ArrayIterator( $array);
$obj->seek(21); // Set to right position
while( $obj->valid()){ // Whether we do have valid offset right now
echo $obj->current() . "\n";
$obj->next(); // Switch to next object
}
$i = 0;
foreach ($query)
{
if ($i++ < 20) continue;
/* php code to execute if record 21+ */
}
if want to skipped some index then make an array with skipped index and check by in_array function inside the foreach loop if match then it will be skip.
Example:
//you have an array like that
$data = array(
'1' => 'Hello world',
'2' => 'Hello world2',
'3' => 'Hello world3',
'4' => 'Hello world4',
'5' => 'Hello world5',// you want to skip this
'6' => 'Hello world6',// you want to skip this
'7' => 'Hello world7',
'8' => 'Hello world8',
'9' => 'Hello world8',
'10' => 'Hello world8',//you want to skip this
);
//Ok Now wi make an array which contain the index wich have to skipped
$skipped = array('5', '6', '10');
foreach($data as $key => $value){
if(in_array($key, $skipped)){
continue;
}
//do your stuf
}
You have not told what "records" actually is, so as I don't know, I assume there is a RecordIterator available (if not, it is likely that there is some other fitting iterator available):
$recordsIterator = new RecordIterator($records);
$limited = new LimitIterator($recordsIterator, 20);
foreach($limited as $record)
{
...
}
The answer here is to use foreach with a LimitIterator.
See as well: How to start a foreach loop at a specific index in PHP
I'm not sure why you would be using a foreach for this goal, and without your code it's hard to say whether this is the best approach. But, assuming there is a good reason to use it, here's the smallest version I can think of off the top of my head:
$count = 0;
foreach( $someArray as $index => $value ){
if( $count++ < 20 ){
continue;
}
// rest of foreach loop goes here
}
The continue causes the foreach to skip back to the beginning and move on to the next element in the array. It's extremely useful for disregarding parts of an array which you don't want to be processed in a foreach loop.
for($i = 20; $i <= 68; $i++){
//do stuff
}
This is better than a foreach loop because it only loops over the elements you want.
Ask if you have any questions
array.forEach(function(element,index){
if(index >= 21){
//Do Something
}
});
Element would be the current value of index.
Index increases with each turn through the loop.
IE 0,1,2,3,4,5;
array[index];

PHP: Getting to a key in mulitdimensional array?

I have an array like
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
)
How can I get a key by providing a value?
e.g. if i search for "buffaloes" array_search may return "2".
Thanks
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
);
function findInArray($term, $array) {
foreach($array as $key => $val) {
if(in_array($term, $val, true)) {
return $key;
}
}
}
echo findInArray('buffaloes', $myArray); // 2
echo findInArray(78, $myArray); // 2
function asearch($key, $myArray) {
for ($i = 0; $i < sizeof($myArray); $i++) {
if ($myArray[$i][0] == $key) {
return $i;
}
}
return -1; # no match
}
Though, you'd probably want to restructure your array to:
$myarray = array(
'dogs' => 98,
'cats' => 56,
'buffaloes' => 78
);
And just do:
$myArray['buffaloes']; # 78
The only way you can do it is to iterate over every item and preform a Linear Search
$i = -1;
foreach ($myArray as $key => $item){
if ( $item[0] == 'buffaloes' ){
$i = $key;
break;
}
}
//$i now holds the key, or -1 if it doesn't exist
As you can see, it is really really inefficient, as if your array has 20,000 items and 'buffaloes' is the last item, you have to make 20,000 comparisons.
In other words, you need to redesign your data structures so that you can look something up using the key, for example a better way may be to rearrange your array so that you have the string you are searching for as the key, for example:
$myArray['buffaloes'] = 76;
Which is much much faster, as it uses a better data structure so that it only has to at most n log n comparisons (where n is the number of items in the array). This is because an array is in fact an ordered map.
Another option, if you know the exact value of the value you are searching for is to use array_search
I never heard of built in function. If you want something more general then above solutions you shold write your own function and use recursion. maybe array_walk_recursive would be helpful
You can loop over each elements of the array, testing if the first element of each entry is equal to "buffaloes".
For instance :
foreach ($myArray as $key => $value) {
if ($value[0] == "buffaloes") {
echo "The key is : $key";
}
}
Will get you :
The key is : 2
Another idea (more funny ?), if you want to whole entry, might be to work with array_filter and a callback function that returns true for the "bufalloes" entry :
function my_func($val) {
return $val[0] == "buffaloes";
}
$element = array_filter($myArray, 'my_func');
var_dump($element);
Will get you :
array
2 =>
array
0 => string 'buffaloes' (length=9)
1 => int 78
And
var_dump(key($element));
Gves you the 2 you wanted.

Categories