John Davidson

arrays - usort and compare function with arguments PHP

0 comments
Message:


I have question
My code works but i dont understand what is $x[1] and $y[1] in function
I tryed $x[0], $x[1], $x[2], $y[0], $y[1], $y[2] and dont get the logical output ? Where i am wrong to understand ? Please if someone can help me ?


<?php
$products = array( array('TIR', 'Tires', 100),
array('OIL', 'Oil', 10),
array ('SPK', 'Spark Plugs', 4));

//print_r ($products); echo '<br />';

function compare($x, $y) {
if ($x[1] == $y[1]) {
return 0;
} else if ($x[1]<$y[1]) {
return -1;
} else {
return 1;
}
}

usort ($products, 'compare');

echo compare('Tires', 'Tires' );
echo compare('Oil', 'Spark Plugs' );
echo compare('Spark Plugs', 'Oil' );
echo compare('Tires', 'Tires');
echo '<br />';

Output is for this code for echo 1, 2, 3, 4:


0
-1
1
0


My Answer:
In the `compare` function, `$x[1]` and `$y[1]` are referring to the second element in the arrays `$x` and `$y` respectively. In this case, the second element in each sub-array of the `$products` array is the product name.

When you call the `compare` function with strings like 'Tires', 'Oil', etc., you are not passing arrays as arguments, so `$x[1]` and `$y[1]` are not valid. That's why you are not getting the expected output.

If you want to compare strings directly, you can modify the `compare` function to take strings as arguments like this:

php
function compare($x, $y) {
if ($x == $y) {
return 0;
} else if ($x < $y) {
return -1;
} else {
return 1;
}
}


Then you can call the function like this:

php
echo compare('Tires', 'Tires' );
echo compare('Oil', 'Spark Plugs' );
echo compare('Spark Plugs', 'Oil' );
echo compare('Tires', 'Tires');
echo '
';


This will give you the correct output for comparing strings directly.

Rate this post

3 of 5 based on 3811 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us